Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo Only Return Elements of Array Matching Query [duplicate]

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.

like image 892
KJ3 Avatar asked Oct 26 '15 18:10

KJ3


2 Answers

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"}}}});
like image 43
mirwaleed Avatar answered Sep 23 '22 22:09

mirwaleed


Alternative not exact you want

db.items.aggregate(
      {$unwind:"$items"},
      {$match:{"items.return":true}}
)
like image 105
Alok Deshwal Avatar answered Sep 23 '22 22:09

Alok Deshwal