Querying Nested List Existence in Mongo

北慕城南 提交于 2019-12-08 18:53:30

问题


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


回答1:


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




回答2:


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:




回答3:


Haven't tested, but I think the query you want is

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

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



来源:https://stackoverflow.com/questions/8583179/querying-nested-list-existence-in-mongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!