以下是样本文件
[
{
"name": "john"
"attribute":[
{
nameAttr: "abc"
tagAttr: "zxs"
},
{
nameAttr: "asd"
tagAttr: "zxs"
},
{
nameAttr: "lll"
tagAttr: "zxs"
},
]
},
{
"name": "john"
"attribute":[
{
nameAttr: "abc"
tagAttr: "zxs"
},
{
nameAttr: "sss"
tagAttr: "zxs"
},
{
nameAttr: "asd"
tagAttr: "zxs"
},
]
},
]
我想将所有常见的nameAttr输出都输出为[“ abc”,“ asd”],因为它们在两个文档中都是常见的,所以我只能使用project来投影nameAttr,但是不知道如何继续进行db.collection.aggregate([
{
$project: {
"attribute.nameAttr": 1,
}
}
])
您可以使用$ group将所有属性名称收集到一个数组数组中,然后将$ reduce与$ setIntersection一起使用以获取通用属性名称:
db.collection.aggregate([
{
$group: {
_id: null,
attributes: { $push: "$attribute.nameAttr" }
}
},
{
$project: {
commonAttributes: {
$reduce: {
input: "$attributes",
initialValue: { $arrayElemAt: [ "$attributes", 0 ] },
in: { $setIntersection: [ "$$value", "$$this" ] }
}
}
}
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句