Reputation: 89
I have a complex group query.
Data is as follows:
Aggregation as follows:
Therefore after execution lets say result would be :
...
},
"_id" : {
"name" : "abc"
},
"amount" : 45.0,
"count" : 4.0,
"desc" : {
"value" : "Laptop", // based on highest sum amount in group:'abc' i.e. 25.0 for laptop
"count" : 5061.72, // (56*100)^2 + (44*100)^2
"percent" : 25.0*100/45.0 = 56.0
},
...
Test Data Link: MonogoDb Playground
Udpated: 07/11/2019
Added example for calculating count
Hope I was clear. Kindly help.
Upvotes: 0
Views: 296
Reputation: 4363
Don't understand the calculation you need for count. However, here's the query you can use to fit your need :
db.collection.aggregate([
{
$match: {
"doc_id": 1
}
},
{
$group: {
_id: {
name: "$name",
desc: "$desc"
},
amount: {
$sum: "$amount"
},
count: {
$sum: 1
},
}
},
{
$sort: {
"_id.name": 1,
"amount": -1
}
},
{
$group: {
_id: "$_id.name",
amount: {
$sum: "$amount"
},
count: {
$sum: "$count"
},
desc: {
$first: {
value: "$_id.desc",
descAmount: "$amount"
}
}
},
},
{
$addFields: {
"desc.percent": {
$multiply: [
{
$divide: [
"$desc.descAmount",
"$amount"
]
},
100
]
}
}
}
])
The tip is to group twice, with a sort between, to get sub-total and first element (the one with the biggest sub-total for each name). Now you can adapt you count calculation as you need.
Upvotes: 2