For anyone who might fall into this again, as @Anand said, it had to do with the type of the field. Always make sure it is of a "summable" type like int, double, float, etc.
MongoDB $group with nested object key $sum
-
30-06-2023 - |
题
The object structure is as follows:
{
"_id" : ObjectId("53434bfe234416601c8b4567"),
"package" : {
"id" : "3",
"title" : "P3",
"price" : "8.00",
"votes" : "8",
"created_at" : "2014-04-08 00:29:35",
"updated_at" : "2014-04-08 00:31:39"
},
"status" : "success",
"user_id" : "5341dd9c234416de758b4570",
"updated_at" : ISODate("2014-04-08T01:08:52.168Z"),
"created_at" : ISODate("2014-04-08T01:08:14.849Z")
}
What I'm trying to do is collect the sum of package.price
with this:
db.transactions.aggregate({
$group:{
_id: null,
'total': {$sum: "$package.price"}
}
})
And the total
is always int 0
, here's the result:
{
"result" : [
{
"_id" : null,
"total" : 0
}
],
"ok" : 1
}
解决方案
不隶属于 StackOverflow