问题
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