每个用户获得总支出金额

时间:2016-07-19 10:44:47

标签: mongodb aggregation-framework

所以在我的mongo数据库中,每个用户都有很多类似于此的记录:

{ "_id" : ObjectId("563d32e1f91e50523787ad2c"), "userId" : ObjectId("563cedfb86aa990cf500000d"), "price" : NumberLong(200)}
{ "_id" : ObjectId("563d32eaf91e50523787adb6"), "userId" : ObjectId("563cedfb86aa990cf500000d"), "price" : NumberLong(500)}

我需要实现的是为每个用户获取价格字段的总和。 顺便说一句,我有大约100万用户和大约2-8的价格记录。

shell查询的外观如何? 感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用userId计算字段组的总和aggregate

db.device.aggregate([{
    $group: {
        "_id": "$userId",
        "totalAmount": { $sum: "$price"}
    }
}])

检查https://docs.mongodb.com/manual/reference/operator/aggregation/sum/

相关问题