mongodbaggregation-framework

MongoDB Aggregation - match if value in array


I have a collection that I'm performing an aggregation on and I've basically gotten it down to

{array:[1,2,3], value: 1},
{array:[1,2,3], value: 4}

How would I perform an aggregation match to check if the value is in the array? I tried using {$match: {"array: {$in: ["$value"]}}} but it doesn't find anything.

I would want the output (if using the above as an example) to be:

{array:[1,2,3], value:1}

Solution

  • A slight variation based on @chridam's answer:

    db.test.aggregate([
        { "$unwind": "$array" },
        { "$group": {
                      _id: { "_id": "$_id", "value": "$value" },
                      array: { $push: "$array" },
                      mcount: { $sum: {$cond: [{$eq: ["$value","$array"]},1,0]}}
                    }
        },
        { $match: {mcount: {$gt: 0}}},
        { "$project": { "value": "$_id.value", "array": 1, "_id": 0 }}
    ])
    

    The idea is to $unwind and $group back the array, counting in mcount the number of items matching the value. After that, a simple $match on mcount > 0 will filter out unwanted documents.