MongoDB - 总和 [英] MongoDB - Aggregate Sum
问题描述
我正在尝试计算在我们的数据库中进行跟踪所花费的总金额.每个订单文档都包含一个字段total_price"
I am attempting to calculate the total amount of money spent being tracked inside of our database. Each order document contains a field "total_price"
我正在尝试使用以下代码:
I am attempting to use the following code:
db.orders.aggregate({
$group: {
_id: null,
total: {$sum: "$total_price"}
}
})
不幸的是,我得到的唯一输出是: { "result" : [ { "_id" : null, "total" : 0 } ], "ok" : 1 }
Unfortunately, the only output I get is: { "result" : [ { "_id" : null, "total" : 0 } ], "ok" : 1 }
但要验证实际存储了数字数据,只是没有汇总:db.orders.find()[0].total_price
这会导致 8.99
But to verifiy there is actually numerical data stored, and just not being totaled: db.orders.find()[0].total_price
this results in 8.99
任何帮助将不胜感激.我使用 MongoDB 的经验很少.目前我只介绍了基础知识.
Any help would be greatly appreciated. I have very little experience using MongoDB. I've only covered the basics at this point.
提前谢谢你.
推荐答案
$sum
仅适用于整数、长整数和浮点数.目前,没有运算符可以将字符串解析为数字,尽管这非常有用.您可以按照 Mongo convert all 中的说明自行执行此操作存储为字符串的数字字段,但这会很慢.
$sum
only works with ints, longs and floats. Right now, there is no operator to parse a string into a number, although that would be very useful. You can do this yourself as is described in Mongo convert all numeric fields that are stored as string but that would be slow.
我建议您确保您的应用程序将数字存储为 int/long/float,并编写一个脚本来迭代所有文档并更新值.我还建议您在 https://jira.mongodb.org/browse/SERVER 添加功能请求 添加一个将字符串转换为数字的运算符.
I would suggest you make sure that your application stores numbers as int/long/float, and that you write a script that iterators over all your documents and updates the value. I would also suggest that you add a feature request at https://jira.mongodb.org/browse/SERVER to add an operator that converts a string to a number.
这篇关于MongoDB - 总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!