下面是我的架构:
[{
"attributes":[
{
"attrId":"123",
"values":[
{"name": "asd"},
{"name": "bcc"}
]
},
{
"attrId":"456",
"values":[
{"name": "zzz"},
{"name": "bcc"}
]
}
]
},
{
"attributes":[
{
"attrId":"123",
"values":[
{"name": "asd"},
{"name": "bcc"}
]
},
{
"attrId":"456",
"values":[
{"name": "kkk"},
{"name": "bcc"}
]
}
]
}]
我希望输出为:
[{123:["asd","ccc"]}]
即返回 attrId
和值,如果所有值都与所有其他文档匹配,
我正在考虑将值转换为字符串,如“asdbcc”,以便于比较。
最佳答案
你可以试试,
$group
由 null 组成根对象数组并获取根中对象的总数$unwind
解构我们在上面阶段创建的root
数组$unwind
解构root.attributes
数组$group
通过root.attributes.attrId
和root.attributes.values
并获取分组文档的总数和值以获得 k (key) 作为attrId
和 v(value) 作为values
对象的值数组,使用$map
并获取第一个totalCount
字段$match
expression using$expr
检查公共(public)文档计数和总根对象文档是否相等然后返回匹配文档$replaceRoot
从values
数组的$arraToObject
转换后替换对象
db.collection.aggregate([
{
$group: {
_id: null,
root: { $push: "$$ROOT" },
totalCount: { $sum: 1 }
}
},
{ $unwind: "$root" },
{ $unwind: "$root.attributes" },
{
$group: {
_id: {
attrId: "$root.attributes.attrId",
values: "$root.attributes.values"
},
values: {
$addToSet: {
k: "$root.attributes.attrId",
v: {
$map: {
input: "$root.attributes.values",
in: "$$this.name"
}
}
}
},
count: { $sum: 1 },
totalCount: { $first: "$totalCount" }
}
},
{ $match: { $expr: { $eq: ["$count", "$totalCount"] } } },
{ $replaceRoot: { newRoot: { $arrayToObject: "$values" } } }
])
关于javascript - 从 MongoDB 中的嵌套数组中查找公共(public)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64661342/