问题
It's hard for me to explain what I want to get, so I will show an example:
I have objects:
{name: 'steve', received: 100} {name: 'carolina', received: 70}
{name: 'steve', 'received: 30} {name: 'andrew', received: 10}
I can do:
{ $group :
{ _id : '$name',
sum : { "$sum" :'$received' },
},
},
And i will get:
Steve received 130 (100 +30)
Carolina received 70
Andrew received 10
But I need something like that:
Steve received 130 (100 +30)
Everyone else received 80 (70+10)
How can I get this effect?
回答1:
You can specify a condition with the $sum
accumulator operator in the grouping:
db.test.aggregate( [
{
$group : {
_id : null,
steve_received: {
$sum: {
$cond: [ { $eq: [ "$name", "steve" ] }, "$received", 0 ]
}
},
others_received: {
$sum: {
$cond: [ { $ne: [ "$name", "steve" ] }, "$received", 0 ]
}
}
}
},
{
$project: { _id: 0 }
}
] )
The above aggregation returns: { "steve_received" : 130, "others_received" : 80 }
来源:https://stackoverflow.com/questions/60311604/aggregate-and-sum-by-one-key-and-rest