I have a collection with entries that look like :
{
"userid": 1,
"contents": [
{ "tag": "whatever", "value": 100 },
{"tag": "whatever2", "value": 110 }
]
}
I'd like to be able to query on that collection and returning only one part of the array : the one matching the query. I'm trying to use the $ positional operator to do so but it hasn't worked so far.
Here is more precisely what I'd like to do :
collection.find({'contents.tag':"whatever"},{'contents.$.value':1})
As a result I expect sth with only the value corresponding to the entry in the array that matched query, which is 100 in this case.
Do you know what's wrong ? I was thinking that maybe the $ operator can only be used for update and not for querying. Anyone in the know ?
Thanks !
collection.find({'contents.tag':'whatever'},{'contents.value':1})
would be enough and doesn't need a positional operator. Nevertheless (as Ryan already mentioned in his answer) it's necessary to pull the field out of the returned array (which will also include the doc's_id
) on app-side. Drawback is the fact afindOne
orlimit(1)
concerning your nested array won't work, which wouldn't be a prob if you don't expect more than 1 result. – Wengert