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 specifies items.return = true
and it should return:
{
_id: "55ef729a66d78d24008xxxx",
name: "The right one"
items: [// 2 element array]
}
I've seen a lot of people suggest using $elemMatch, such as this question, but as it says, this
only return the first match
but this just returns the parent documents that have some value in the array matching items.return. So in the above example it would return all 3 array elements.
I want to completely ignore these array values in my return. I don't want to do it in the client, because I do a project using the items _id and don't want to waste the project if I don't need it.
One alternative is to use $elemMatch
. Check the docs, worth to notice is that it only returns first match!
db.items.find({}, {items: {$elemMatch: {return: "admin"}}}});
Alternative not exact you want
db.items.aggregate(
{$unwind:"$items"},
{$match:{"items.return":true}}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With