MongoDB sum()数据

时间:2014-04-15 21:33:17

标签: mongodb aggregation-framework nosql

我是mongoDB和nosql的新手,获得总和的语法是什么?

在MySQL中,我会做这样的事情:

SELECT SUM(amount) from my_table WHERE member_id = 61;

我如何将其转换为MongoDB?这是我尝试过的:

db.bigdata.aggregate({
    $group: {
        _id: {
            memberId: 61, 
            total: {$sum: "$amount"}
        }
    }
})

3 个答案:

答案 0 :(得分:3)

使用http://docs.mongodb.org/manual/tutorial/aggregation-zip-code-data-set/作为参考:

db.bigdata.aggregate(
{
    $match: {
        memberId: 61
    }
},
{
    $group: {
        _id: "$memberId",
        total : { $sum : "$amount" }
    }
})

来自MongoDB文档:

  

聚合管道是基于数据处理管道概念建模的数据聚合框架。文档进入多阶段管道,将文档转换为聚合结果。

答案 1 :(得分:1)

最好先匹配然后匹配组,这样系统才会对过滤后的记录执行组操作。如果先执行组操作,系统将对所有记录执行组,然后选择memberId = 61的记录。

db.bigdata.aggregate( 
{ $match : {memberId : 61 } },
{ $group : { _id: "$memberId" , total : { $sum : "$amount" } } }                       
)

答案 2 :(得分:0)

db.bigdata.aggregate( 
{ $match : {memberId : 61 } },
{ $group : { _id: "$memberId" , total : { $sum : "$amount" } } }                       
)

如果要求数据不是数组的一部分,如果要对文档中某些数组中存在的数据求和,则使用

db.collectionName.aggregate(
{$unwind:"$arrayName"},   //unwinds the array element

{
$group:{_id: "$arrayName.arrayField", //id which you want to see in the result
total: { $sum: "$arrayName.value"}}   //the field of array over which you want to sum
})

并将得到这样的结果

{
    "result" : [
        {
            "_id" : "someFieldvalue",
            "total" : someValue
        },
        {
            "_id" : "someOtherFieldvalue",
            "total" : someValue
        }
    ],
    "ok" : 1
}
相关问题