MongoDB : use $ positional operator for querying

Johanisma picture Johanisma · Jun 8, 2011 · Viewed 11.1k times · Source

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 !

Answer

Ryan picture Ryan · Jun 8, 2011

Yes, you are correct - the positional operator is used for updating an object.

The solution for now would be to return the array an pull the field out in your application.

There is an open enhancement request for this feature (in queries):

https://jira.mongodb.org/browse/SERVER-828

For more information on the positional operator, see:

http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator