array field filtering by index or another field

13 views
Skip to first unread message

Dmitry B.

unread,
May 11, 2016, 12:43:23 PM5/11/16
to mongodb-user
When filtering an array, is it possible:

   1. filter by item index (e.g. get all array elements but the first)?
   2. filter by value in another field within the same document that contains the array field?

Consider a document:

{
    _id: 1, 
     first_seen_on: 20160312, 
     seen_on: [20160312, 20160313, 20160324] 
}

I need the seen_on array to become [20160313, 20160324]

This doesn't seem to work (I think $first_seen_on is treated as literal value): 'repeats': 
   {
       '$filter': { 
           'input': '$seen_on', 
           'as': 'date', 
           'cond': {'$ne': ['$date', '$first_seen_on']
       }
   }

Wan Bachtiar

unread,
May 16, 2016, 9:00:37 PM5/16/16
to mongodb-user

I need the seen_on array to become [20160313, 20160324]

Hi Dmitry,

Given your document example, you could filter the value of seen_on field with first_seen_on field like below:

db.collection.aggregate([
    { $project: 
        { filtered : 
            { $filter: 
                { input: "$seen_on", 
                  as: "date", 
                  cond: {$ne:["$$date", "$first_seen_on"]}
                }
            }
        }
    }
]);

Note that you need to refer to date using double dollar $$ sign. See $filter for more info.

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages