gpt4 book ai didi

mongodb - 聚合数组中的对象匹配多个条件的文档

转载 作者:行者123 更新时间:2023-12-03 20:30:51 24 4
gpt4 key购买 nike

我有一个包含类似这样的文档的集合:

{
"_id": ObjectId("xxxxx"),
"item": [
{ "property": ["attr1", "+1"] },
{ "property": ["attr2", "-1"] }
]
}

{
"_id": ObjectId("xxxxy"),
"item": [
{ "property": ["attr1", "-1"] },
{ "property": ["attr2", "0"] }
]
}

{
"_id": ObjectId("xxxxz"),
"item": [
{ "property": ["attr1", "0"] },
{ "property": ["attr2", "+1"] }
]
}

最好使用聚合管道,当且仅当任何一个属性匹配多个条件时,有没有办法匹配文档?

例如,我想要一个查询,其中数组中的一个对象与这两个条件都匹配:
("item.property": "attr1") AND ("item.property": /^\+/)

也就是说,包含“attr1”和以“+”开头的元素的单个属性。

但是,使用我当前的查询,如下所示:
collection.aggregate(
{ $match:
{ $and:
[
{ "item.property": "attr1" },
{ "item.property": /^\+/ }
]
}
}

这将匹配第一个和最后一个文档,因为它们都包含一个带有“attr1”的属性和一个带有“+”的元素。但是,我不希望此查询与最后一个文档匹配,因为以“+”开头的元素不属于数组中的同一对象。

有没有办法使用聚合框架来实现这种行为?

最佳答案

您可以将以下查询与 $elemMatch 一起使用匹配数组的两个值。

就像是

db.collection_name.aggregate({
"$match": {
"item": {
"$elemMatch": {
"property.0": "attr1",
"property.1": /^\+/
}
}
}
});

此外,您可以使用 $all 运算符,如果您不想引用数组索引。
db.collection_name.aggregate({
"$match": {
"item": {
"$elemMatch": {
"property": {
"$all": [
"attr1",
/^\+/
]
}
}
}
}
});

关于mongodb - 聚合数组中的对象匹配多个条件的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47825790/

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