You have two challenges, first you have to convert field values to field names. This is achieved with $objectToArray
and $arrayToObject
.
Second you have to translate all documents into one document. For this I use $group
and $reduce
db.collection.aggregate([
{ $unset: "_id" },
// transform field values into field names
{ $set: { data: { $objectToArray: "$$ROOT" } } },
{
$set: {
data: {
$map: {
input: "$data",
in: { k: "$$this.v", v: 1 }
}
}
}
},
{ $replaceRoot: { newRoot: { $arrayToObject: "$data" } } },
// Merge all documents into one
{
$group: {
_id: null,
data: { $push: "$$ROOT" }
}
},
{
$replaceRoot: {
newRoot: {
$reduce: {
input: "$data",
initialValue: {},
in: { $mergeObjects: [ "$$value", "$$this" ] }
}
}
}
}
])
See Mongo playground
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…