蒙戈$cond,如果表达式不像$match那样工作



我有一个带有"parent"场。

[
{
"parent": "P1",
"tagGroups": [],

},
{
"parent": "P1",
"tagGroups": [
{
group: 1,
tags: {
tag1: {
value: true
},
tag2: {
value: "foo"
},

}
},
{
group: 2,
tags: {}
}
]
},
{
"parent": "P2",
"tagGroups": [],

}
]

我想发出一个请求,当至少有一个与我的标准tag1匹配时,检索具有相同父级的所有文档。Value = true

预期:

[
{
"parent": "P1",
"tagGroups": [],
},
{
"parent": "P1",
"tagGroups": [
{
group: 1,
tags: {
tag1: {
value: true
},
tag2: {
value: "foo"
},
}
},
{
group: 2,
tags: {}
}
]
}
]

为此,我想使用$cond标记每个文档,然后按父级分组。

https://mongoplayground.net/p/WiIlVeLDrY-

但是"if"部分工作方式似乎与$match

不同https://mongoplayground.net/p/_jcoUHE-aOu

你有其他有效的方法来做这种查询吗?

编辑:我可以使用查找阶段,但我害怕糟糕的性能

感谢

您没有提到您想要实现什么,但是您希望您的试用代码(第一个链接)应该可以工作。您需要在查询

中使用$in而不是$eq
db.collection.aggregate({
"$addFields": {
"match": {
"$cond": [
{ $in: [ true, "$tagGroups.tags.tag1.value" ] }, 1, 0] }
}
},
{
"$group": {
"_id": "$parent",
"elements": { "$addToSet": "$$ROOT" },
"elementsMatch": { "$sum": "$match" }
}
},
{ "$match": { "elementsMatch": { $gt: 0 } }},
{ "$unwind": "$elements"}
)

Working Mongo playground

注意:你问的是有效率的方式。最好发布预期结果

最新更新