MongoDB-总计 [英] MongoDB - Aggregate Sum

查看:73
本文介绍了MongoDB-总计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算在我们的数据库中被跟踪花费的总金额.每个订单文档都包含一个字段"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全部转换以字符串形式存储的数字字段,但这会很慢.

$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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆