Search code examples
mongodbnode-mongodb-native

Mongodb return documents AND the array elements that match query


How do I query a collection to return me all the documents in it, which have in the subfield "list", which is an array, at least one element with "time" > 100, and return me in the "list" all elements that satisfy this condition, not just the first. $ and $elemMatch only returns the first, but I want them all. How do I do it?


Solution

  • Yes, the aggregation framework will help you do this. Something like this query should work:

    db.collection.aggregate( 
        { $unwind : "$list" }, // deconstruct the array
        { $match : { list : { $gt : 100 } } }, // match based on your condition
        { $group : { _id : "$_id", list : { $push : "$list" } } } // rebuild array
    )
    

    You'll have to change this query based on your exact data structure, but that's the general idea.