find the document from sub array?

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

I have a collection with documents that look like this:

"awards" : {     "oscars" : [         {"award": "bestAnimatedFeature", "result": "won"},         {"award": "bestMusic", "result": "won"},         {"award": "bestPicture", "result": "nominated"},         {"award": "bestSoundEditing", "result": "nominated"},         {"award": "bestScreenplay", "result": "nominated"}     ],     "wins" : 56,     "nominations" : 86,     "text" : "Won 2 Oscars. Another 56 wins and 86 nominations." } 

What query document would we use in a find() command to return all movies in the my_collection collection that either won or were nominated for best picture?

回答1:

You need to use the dot notation to specify an exact match on the embedded document and use the $in operator to select those documents that won or were nominated for best picture

You shouldn't use the $or operator here because it will perform a collection scan if not all the clauses are supported by indexes as mention in the documentation.

db.my_collection.find({      'awards.oscars.award': 'bestPicture',      'awards.oscars.result': { '$in': [ 'won', 'nominated' ] }  } ) 


回答2:

According to the MongoDB Query documentation, you can match a field in an embedded document within an array by concatenating its name to the name of the array like so:

db.my_collection.find(   {     'awards.oscars.award': 'bestPicture',     $or: [       { 'awards.oscars.result': 'won' },       { 'awards.oscars.result': 'nominated' }     ]   } ) 


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