Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB : use $ positional operator for querying

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 !

like image 912
Johanisma Avatar asked Jun 08 '11 14:06

Johanisma


People also ask

What is positional operator in MongoDB?

The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.

How do I query data in MongoDB?

To query data from MongoDB collection, you need to use MongoDB's find() method.

What is $[] in MongoDB?

$[] The all positional operator $[] indicates that the update operator should modify all elements in the specified array field. The $[] operator has the following form: { <update operator>: { "<array>.$[]" : value } }


1 Answers

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

like image 188
Ryan Avatar answered Oct 16 '22 23:10

Ryan