I have this array of results in the first stage of the aggregation pipeline, using a $match
:
[
{ a: 1, b: 2 },
{ a: 3, b: 4 }
]
Now I want to sum all of the A's and B's and also still have them so I will have something like this as a result:
{
total_sum: 10,
items: [...] // first and second objects ofcourse
}
I have tried to $group
and $push
, however, push only pushes specific fields from the object and I need to name A and B, instead just of parse all of them.
How can I do it?
CodePudding user response:
$set
- Create new fieldtotal
to suma
andb
.$group
- Group bynull
, indicate to sum alltotal
and add the document initems
array.
With $$ROOT
it will add the whole document.
items: {
$push: "$ROOT"
}
If you want just some fields only, then specify the (desired) document pattern.
items: {
$push: {
A: "$a",
B: "$b"
}
}
$unset
(If use$push $$ROOT
) - Removetotal
field fromitems
field.
db.collection.aggregate([
{
$set: {
total: {
$sum: [
"$a",
"$b"
]
}
}
},
{
$group: {
_id: null,
total_sum: {
$sum: "$total"
},
items: {
$push: "$$ROOT"
}
}
},
{
$unset: "items.total"
}
])