1

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 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']}
            }
2
  • when you say filtering, you refer to the filter stage in the aggregation pipeline? Commented May 11, 2016 at 6:34
  • Filtering an array, like in the sample code I included, in the project stage of the aggregation pipeline. Commented May 11, 2016 at 6:36

1 Answer 1

1

Use $setDifference as follows

db.collection.aggregate([
    {
        "$project": {
            "repeats": {
                "$setDifference": ["$seen_on", ["$first_seen_on"]]
            }
        }
    }
])

Sample Output

/* 1 */
{
    "_id" : 1,
    "repeats" : [ 
        20160313, 
        20160324
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.