Reputation: 35
assume I have these three documents in a collection
{ "num" : 10, "count" : 1 }
{ "num" : 20, "count" : 2 }
{ "num" : 30, "count" : 3 }
Now I want to make one documents with sum of same fields(fields are same in all doc)
{ "num" : 60, "count" : 6 }
How to do that ?
Upvotes: 0
Views: 35
Reputation: 2071
You can write an aggregate query to do that.
$group
with $sum
to calculate the sum$project
operator to remove the id key required by the $group operatordb.collection.aggregate({
$group: {
_id: "",
num: {
$sum: "$num"
},
count: {
$sum: "$count"
}
}
},
{
$project: {
_id: 0,
num: "$num",
count: "$count"
}
})
Upvotes: 1