問題描述
查詢嵌入列表中的數組 (Querying for array in embedded list)
假設我有一個類似於以下內容的 mongo 文檔:
{
'foo':1
'listOfLists' : [ [1,2],[3,4] ]
}
(是的,我知道這不是它“真正”的樣子,但它應該足夠簡單,便於解釋。)
如果我想編寫一個查詢來檢查listsOfLists列表對像是否包含[3,4]的組合,我該怎麼做呢?
可以我做了類似
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.
(by K.Niemczyk、Neil Lunn)