![](/img/trans.png)
[英]MongoDB - Find elements, where field is equal to at least one value at array
[英]Mongodb: Find all documents where at least one array element does not matches?
我在貓鼬中定義了一個小組文檔:
var GroupSchema = new Schema({
name: String,
sections: [{type: ObjectId}]
});
可見,組包含一個節數組。 我也有OBJECTID的所謂archived_sections的另一個數組
我想找到所有至少有一部分不在archived_sections數組中的組。 怎么做?
我試圖像這樣使用$ nin運算符:
Group.find({ sections: { $nin: archived_sections }).exec(function(err, groups){
res.send(groups);
});
但這只是給我的那些組,其sections字段包含一個數組,其中沒有元素與數組archived_sections中的元素匹配。
我想找到所有組,其中“至少一個”部分不在archived_sections數組中。 如何實現呢? 請幫忙
您可以通過將$nin
封裝在$elemMatch
運算符中來做到這一點,以便將$nin
分別應用於sections
每個元素,而不是作為一組元素進行應用:
Group.find({ sections: { $elemMatch: { $nin: archived_sections } } })
.exec(function(err, groups){
res.send(groups);
}
);
如果至少一個元素滿足$elemMatch
查詢,則文檔匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.