Reputation: 141
I've the follwing items in a collection:
{ "_id":1, "vals": [ { a:1, b:2, c:0 }, { a:1, b:2, c:1 }, { a:1, b:2, c:2 } ] }
{ "_id":2, "vals": [ { a:1, b:2, c:1 }, { a:1, b:2, c:2 }, { a:1, b:2, c:0 } ] }
{ "_id":3, "vals": [ { a:1, b:2, c:2 }, { a:1, b:2, c:0 }, { a:1, b:2, c:1 } ] }
I want to find all item with ( vals.c > 1 ), but only considering always the first element in array.
Doing that in the right way I would get only items: _id:2, _id:3 in the result.
Taking the follwing find-request I get all items instead.
db.items.find( { vals: { $elemMatch: { c: { $gte:1 } } }, { "vals.$": 1 } } )
Any idea how to make the request, to get the wished result?
Upvotes: 1
Views: 113
Reputation: 24007
Perhaps surprisingly, you can do it like so:
db.items.find({ 'vals.0.c': { $gte: 1 } })
You can choose to return only the zeroeth array element in your query results with the $slice query-projection operator:
db.items.find({ 'vals.0.c': { $gte: 1 } }, {'vals': {'$slice': 1}})
See $slice, and you may also be interested in the new $elemMatch projection operator.
Upvotes: 1