If you see, age field and using sum operator in mongodb is the same as normal SQL count operator. Can you please explain how to use correct sum in mongodb
> db.test.find()
{
"_id" : ObjectId("544654d01cdcaf6a66c188e8"),
"age" : 23,
"name" : "Alex"
}
{
"_id" : ObjectId("544654f01cdcaf6a66c188ec"),
"age" : 33,
"name" : "Alex"
}
{
"_id" : ObjectId("544654fb406947798c239544"),
"age" : 14,
"name" : "Alex"
}
{
"_id" : ObjectId("5446550a406947798c239547"),
"age" : 25,
"name" : "Oleg"
}
{
"_id" : ObjectId("54465523406947798c23954a"),
"age" : 15,
"name" : "Oleg"
}
{
"_id" : ObjectId("54465538406947798c23954e"),
"age" : 10,
"name" : "Mark"
}
> db.test.aggregate([{$group:{_id:"$name","age":{$sum:1}}}])
{ "_id" : "Mark", "age" : **1** }
{ "_id" : "Oleg", "age" : **2** }
{ "_id" : "Alex", "age" : **3** }
You can write as
db.test.aggregate([{$group:{_id:"$name","age":{$sum:"$age"}}}])
to sum as you expected.
The operand of $sum is an expression, sum is made according to the final result of this expression, added to filed age for this group.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments