Reputation: 2990
a doc {"m":[1,2,3], "others":xxx}
, get the first element in array 'm' by:
db.find({query},{"m":{$slice:1}, "m":1})
the return is {"m":[1]}
, the element in doc is an array. But in this query, only one element in array will be get, so I don't need the return doc contain array which has only one element. This is like SQL local variable in sub-query. The element I want has no name in original doc, if I want get it then I need to make a name for it, the doc returned I wanted is like: {"localVariable":1} rather than {"m":[1]}
I try to project out the first element by:
db.find({query},{"m":{$slice:1}, "m.1":1})
but this don't work.
Upvotes: 5
Views: 2321
Reputation: 151190
You seem to be looking for a positional $
operator match. It works like this:
db.collection.find({ m: 2 },{ "m.$": 1 })
That will return you the matched element
If you are in fact looking to always get the second element, then you need the two argument form of $slice
:
db.collection.find({ },{ "m": { "$slice": [1,1] } })
Tested output:
db.test.insert({ m: [1,2,3] })
db.test.find({ },{ "m": {$slice: [1,1]} })
{ "_id" : ObjectId("5323cc2770fde63cf1146ba3"), "m" : [ 2 ] }
Upvotes: 1