Reputation: 1259
My Sample data looks like below:
Category response
Privacy 1
Mobile 1
Privacy 1
Privacy 2
I want add new field Total
taken from sum of all response
field values. Required output as below :
Category response Total
Privacy 1 5
Mobile 1 5
Privacy 1 5
Privacy 2 5
How can I get this output in mongodb.
Upvotes: 3
Views: 1203
Reputation: 17915
Update : As value of Total
is not the fixed one, updated answer with question :
/** Using 'facet' as we need docs to be returned in result
* (Can also be done without 'facet' by pushing all docs into an array in '$group' but it may not work for large datasets) */
db.collection.aggregate([
{
$facet: {
data: [ { $match: {} } ], /** Get all docs without any filter */
total: [
{
$group: { /** Group all docs & sum-up 'result' field */
_id: "",
Total: { $sum: "$response" }
}
}
]
}
},
{
$unwind: "$data"
},
{
$unwind: "$total"
},
/** Merge 'total' field into 'data' & make data field as new root for documents */
{
$replaceRoot: { newRoot: { $mergeObjects: [ "$total", "$data" ] } }
}
])
Test : MongoDB-Playground
Old : If Total
is same value for all docs .
If it's the same value needed to be added across all documents in aggregation result then just use aggregation stage $addFields :
{ $addFields : { Total :5 } }
Upvotes: 2