MongoDB: use the $ positional operator for queries

I have a collection with elements that look like this:

{
    "userid": 1, 
    "contents": [ 
            { "tag": "whatever", "value": 100 }, 
            {"tag": "whatever2", "value": 110 } 
    ] 
}

I would like to be able to query this collection and return only one part of the array: the one that matches the request. I am trying to use the $ positional operator for this, but it is not working yet.

Here is more precisely what I would like to do:

collection.find({'contents.tag':"whatever"},{'contents.$.value':1})

As a result, I expect that sth only has a value corresponding to an entry in the array that matches the query, which in this case is 100.

Do you know what happened? I thought that perhaps the $ operator can only be used for updating, not for queries. Somebody knows?

Thank!

+5
source share
4 answers
+7

, , map-reduce .

, , , , , . , .

, , .

Nevertheless, I hope that SERVER-828 will be implemented soon!

0
source

Create a query using $ in instead and add an equal value to the array, this may solve your problem.

$users_array = array(xxxxxxxx,yyyyyy);     
$user = Db::find('fb_users', array(
                            'facebook_id' => array(
                                '$in' => array($users_array)
                            )
                        ));
0
source

All Articles