Querying the existence of a nested list in Mongo

I have a document in Mongo that is structured as follows:

{ "_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 request documents whose play.clicks attribute is a non-empty list. I tried to exist without luck. I thought something like this might work:

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

But I believe that this will only return documents whose first element in the play array contains a non-empty list of clicks.

Any thought on how I can do this?

thanks

+6
source share
3 answers

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

- The correct syntax, however, since plays is a list, the request will match any document with clicks in plays . Thus, it is impossible to find a subset of the array for subelements [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

+7
source

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

+3
source

Not tested, but I think the request you want is

 { "plays.clicks" : { "$size" : 0 } } 

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24size

0
source

Source: https://habr.com/ru/post/904201/


All Articles