gpt4 book ai didi

mongodb - Mongo查询子文档的多个字段

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

假设我有一个这样的集合:

{ "arr" : [ { "name" : "a", "num" : 1 }, { "name" : "a", "num" : 2 } ] },
{ "arr" : [ { "name" : "b", "num" : 1 }, { "name" : "a", "num" : 2 } ] },
{ "arr" : [ { "name" : "b", "num" : 1 }, { "name" : "b", "num" : 2 } ] }

我想查找所有 arr 包含 name = "b"和 num = 2 的子文档的文档。

如果我这样查询:

db.collection.find({
$and: [
{ "arr.name": "b" },
{ "arr.num": 2 }
]
});

它将返回集合中的所有文档,因为它们每个都包含一个子文档,其 name 为“b”或 num 为 2。

我也试过这个:

db.collection.find({
arr: [
{ "name": "b", "num": 2 }
]
});

不会抛出任何错误,但不会返回任何结果。

如何查询MongoDB中的多个子文档字段?

最佳答案

这实际上是$elemMatch运算符是 for 即使它经常被误用。它实质上对数组“内”的每个元素执行查询条件。除非另有明确调用,否则所有 MongoDB 参数都是“与”操作:

db.collection.find({ "arr": { "$elemMatch": { "name": "b", "num": 2  } } })

如果您只期望匹配的字段而不期望匹配字段,您可能还想在此处“投影”整个文件:

db.collection.find(
{ "arr": { "$elemMatch": { "name": "b", "num": 2 } } },
{ "arr.$": 1 }
)

最后解释为什么你的第二次尝试不起作用,这个查询:

db.collection.find({
"arr": [
{ "name": "b", "num": 2 }
]
})

不匹配任何内容,因为没有“arr”包含与您的条件完全匹配的单数元素的实际文档。

你的第一个例子失败了..:

db.collection.find({
$and: [
{ "arr.name": "b" },
{ "arr.num": 2 }
]
});

因为有几个数组元素满足条件,这不只是认为两个条件都适用于同一个元素。这就是 $elemMatch 添加的内容,当您需要匹配多个条件时,这就是您使用它的地方。

关于mongodb - Mongo查询子文档的多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27914664/

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