You can try,
$group
by null and make array of root objects and get count of total objects in root$unwind
deconstructroot
array that we have created in above stage$unwind
deconstructroot.attributes
array$group
byroot.attributes.attrId
androot.attributes.values
and get total count of grouped documents and values to get k(key) asattrId
and v(value) as array of values fromvalues
object using$map
and get firsttotalCount
field$match
expression using$expr
check common document count and total root object document both are equal then return matching documents$replaceRoot
to replace and object after converting from$arraToObject
ofvalues
array
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" } } }
])
CLICK HERE to find out more related problems solutions.