Querying for array in embedded list

谁都会走 提交于 2020-01-16 05:21:06

问题


Supposed I have a mongo document that looks similar to the following:

{
   'foo':1
   'listOfLists' : [ [1,2],[3,4] ]
}

(Yes I am aware this isn't how it "really" looks but it should be simple enough for explanation purposes.)

If I wanted to write a query that would check to see if the listsOfLists list object contains the combination of [3,4], how could I go about doing that?

Could I do something like

collection.find({'listsOfLists' : {'$elemMatch' : [3,4] } })

回答1:


collection.find({ 'listsOfLists': [3,4] }).

It's just a "direct match" on the property. MongoDB will look at each array element automatically. You don't need $elemMatch here.

If you were to use it, you need an operator expression, such as $eq:

collection.find({ 'listsOfLists': { '$elemMatch': { '$eq': [3,4] } } }).

But that of course is not required unless there are "two or more" conditions that actually need to match on the array elements. Which is what $elemMatch is actually for.



来源:https://stackoverflow.com/questions/36439892/querying-for-array-in-embedded-list

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