我有一个带有文档的集合是这样的:
{
"date" : 20200817,
"items" : [
{
"name" : "item1", "values" : ["val1", "val2", "val3"]
},
{
"name" : "item2", "values" : ["val1", "val3", "val4", "val5"]
},
{
"name" : "item3", "values" : ["val1", "val3"]
}
]
}
我想交集(∩)values
是items.name
在["item1", "item2"]
这样的
["val1", "val3"]
我有这个查询:
db.output.aggregate([{
$project: {
output: {
$map: {
input: {
$filter: {
input: "$lists",
cond: {$in: ["$$this.name", ["item1", "item2"]]}
}
}, in: "$$this.values"
}
}
}
},
{
"$project": {
"output": {"$setUnion": "$output"}
}
}])
但结果是
{
"output" : [
["val1", "val2", "val3"],
["val1", "val3", "val4", "val5"]
]
}
我的查询错在哪里?
我能做什么?
谢谢
你可以试试$setUnion
里面$reduce
,
db.output.aggregate([
{
$project: {
output: {
$reduce: {
input: "$items",
initialValue: [],
in: {
$setUnion: [
"$$value",
{
$cond: [
{ $in: ["$$this.name", ["item1", "item2"]] },
"$$this.values",
[]
]
}
]
}
}
}
}
}
])
您的第二个编辑问题,
您可以$setIntersection
在第二个$project
管道阶段内尝试实现的查询。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句