I have a database with the following documents:
{ name: \"John\", a: 20, b: 30, c: 40, d: 50 },
{ name: \"Rich\", a: 20, b: 30, c: 40, d: 50 },
{ na
You can take advantage of $objectToArray and $arrayToObject operators to dynamically read your object keys. To get rid of _id
and name
fields you can $filter by $type.
db.collection.aggregate([
{
$project: {
_id: 0,
fields: {
$filter: {
input: { $objectToArray: "$$ROOT" },
cond: { $eq: [ { $type: "$$this.v" }, "double" ] }
}
}
}
},
{
$unwind: "$fields"
},
{
$group: {
_id: "$fields.k",
total: { $sum: "$fields.v" }
}
},
{
$group: {
_id: null,
aggregates: { $push: { k: "$_id", v: "$total" } }
}
},
{
$replaceRoot: {
newRoot: { $arrayToObject: "$aggregates" }
}
}
])
Mongo Playground