gpt4 book ai didi

MongoDB高级查询: get elements in an array matching a second condition

转载 作者:IT老高 更新时间:2023-10-28 13:27:16 24 4
gpt4 key购买 nike

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

元素:

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

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

这个查询效率高但不满足要求:

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

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

最佳答案

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

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

关于MongoDB高级查询: get elements in an array matching a second condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12924465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com