MongoDB高级查询:获取匹配第二个条件的数组中的元素

MMi*_*ind 6 mongodb

我们有一组具有以下结构的元素:

内容:

{
id : 123,
items : [ { color: "blue", "groups" : [3, 5] }, { color: "red", "groups" : [6, 8] } ]
}

{
id : 124,
items : [ { color: "blue", "groups" : [1, 2] }, { color: "green", "groups" : [5, 9] } ]
}
Run Code Online (Sandbox Code Playgroud)

我们想要一种有效的方法来获取具有颜色为蓝色的项目的元素可以访问组5,9,27,123或56.这应该返回ID为123的元素,但不返回ID为124的元素,因为item必须满足这两个条件.我们希望查询尽可能高效.

此查询有效但不符合要求:

{$and : { "items.groups" : { $in : [5, 9, 27, 123, 56] }, "items.color" : "blue" }} 
Run Code Online (Sandbox Code Playgroud)

它会匹配,id = 124因为它有一个匹配"蓝色"的项目和另一个匹配组9的项目.

Joh*_*yHK 7

您需要使用,$elemMatch因为您希望匹配单个数组元素的多个属性:

db.test.find({ items: { $elemMatch: { 
    color: "blue", 
    groups: { $in: [5, 9, 27, 123, 56] } 
}}});
Run Code Online (Sandbox Code Playgroud)