Mongo Only Returns array elements matching the query.

Given the following JSON example:

{
    _id: "55ef729a66d78d24008xxxx",
    name: "The right one"
    items: [{
        _id: "55ef729a66d78d24008xxxx",
        return: true
    }, {
        _id: "55ef729a66d78d24008xxxx",
        return: true
    }, {
        _id: "55ef729a66d78d24008xxxx",
        return: false
    }]
}

I want to write a query that indicates items.return = true, and it should return:

{
    _id: "55ef729a66d78d24008xxxx",
    name: "The right one"
    items: [// 2 element array]
}

I saw how many people suggest using $ elemMatch, for example question , but as they say, this

returns only the first match

but this just returns parent documents that have some value in the array matching items.return. Thus, in the above example, it will return all 3 elements of the array.

I want to completely ignore these array values ​​in my return. I do not want to do this in the client, because I am doing a project using _id elements and do not want to spend the project if I do not need it.

+4
3

- $elemMatch. , , !

db.items.find({}, {items: {$elemMatch: {return: "admin"}}}});
+2

db.items.aggregate(
      {$unwind:"$items"},
      {$match:{"items.return":true}}
)
+1

You can use the aggregation structure, this is not the best solution, although

db.collection.aggregate([
      {$unwind:'$items'},
      {$match:{'items.return':true}},
      {$group:{_id:'$_id', name: '$name',items:{$push:'$items'}}}
])
0
source

Source: https://habr.com/ru/post/1613244/


All Articles