Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying Nested List Existence in Mongo

I have a document in Mongo that is structured in the following way:

{ 
    "_id" : ObjectId("4eea7237d0ba3a04f20008fb"), 
    "code" : "b2677c2809c844cc9d7e3e4ff8d95b46", 
    "city_id" : 4, 
    "datetime" : ISODate("2011-12-13T18:41:44.062Z"), 
    "plays" : [     
        {   
          "play_id" : 717224,   
          "clicks" : [ ],   
          "order" : 1,  
          "mysql_id" : 145
        }

I want to query for docs whose plays.clicks attribute is a non-empty list. I've tried exists with no luck. I thought that something like this might work:

 db.collection.find({plays.clicks.0: {$exists:true}})

But I believe that this would return only docs whose first element in the plays array contains a non-empty clicks list.

Any thought on how I might get this done?

Thanks

like image 246
Ben Avatar asked Dec 20 '11 23:12

Ben


People also ask

How do I query a nested field in MongoDB?

In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

How do I query an array element in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

What is the preferred method of querying embedded documents in MongoDB?

Use the $elemMatch operator to query embedded documents. Use conditional operators to query embedded documents. Use Visual Query Builder to query embedded documents.


2 Answers

db.collection.find({plays.clicks.0: {$exists:true}})

is the right syntax, however as plays is a list the query will match any document that has clicks in plays. There is no way to retrieve a subset of an Array for subelements in this way[1]. There is a ticket for sub / virtual collections[2]

[1] http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements

[2] https://jira.mongodb.org/browse/SERVER-828

like image 177
Ross Avatar answered Sep 22 '22 05:09

Ross


Save the size of the list as a separate attribute (e.g. num_plays). Then you can query for documents where num_plays is greater than 0:

like image 38
Matt Avatar answered Sep 20 '22 05:09

Matt