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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12924465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 15:58:21  来源:igfitidea点击:

MongoDB advanced query: get elements in an array matching a second condition

mongodb

提问by MMind

We have a collection of elements that has the following structure:

我们有一个具有以下结构的元素集合:

elements:

元素:

{
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] } ]
}

We want an efficient way to get Elements that have an item with color blue accessible to groups 5, 9, 27, 123 or 56. This should return Element with id 123 but not element with id 124 because item must meet both conditions. We want the query to be as efficient as possible.

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

This query is efficient but does not meet the requirement:

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

{$and : { "items.groups" : { $in : [5, 9, 27, 123, 56] }, "items.color" : "blue" }} 

as it will match id = 124because it has an item that matches "blue" and another one that matches group 9.

因为它会匹配,id = 124因为它有一个匹配“blue”的项目和另一个匹配组 9 的项目。

回答by JohnnyHK

You need to use $elemMatchbecause you're looking to match multiple attributes of a single array element:

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

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