Answer the question
In order to leave comments, you need to log in
How to use multiple $sums in MongoDB aggregation?
Hello.
Collection example:
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "status": "ok"}
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "status": "ok"}
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "status": "ok"}
{ "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "status": "ok"}
{ "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "status": "error"}
{ "_id" : {{ "item" : "abc", count: 2 }, {"status":[ "error": 0, "ok": 2 ]}}
{ "_id" : {{ "item" : "jkl", count: 1 }, {"status":[ "error": 0, "ok": 1 ]}}
{ "_id" : {{ "item" : "xyz", count: 2 }, {"status":[ "error": 1, "ok": 1 ]}}
Answer the question
In order to leave comments, you need to log in
In general, it turned out like this (logic - we go from the lowest nesting level, count it, push it to the next level, count, etc.):
db.collection.aggregate({
"$group": {
_id: {
item: "$item",
status: "$status"
},
count: {
$sum: 1
}
}
},
{
"$group": {
_id: {
item: "$_id.item"
},
count: {
$sum: "$count"
},
status: {
"$push": {
status: "$_id.status",
count: "$count"
}
}
}
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question