MongoDB sum() data

…衆ロ難τιáo~ 提交于 2019-12-11 11:26:38

问题


I am new to mongoDB and nosql, what is the syntax to get a sum?

In MySQL, I would do something like this:

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

How would I convert that to MongoDB? Here is what I have tried:

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

回答1:


Using http://docs.mongodb.org/manual/tutorial/aggregation-zip-code-data-set/ for reference you want:

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

From the MongoDB docs:

The aggregation pipeline is a framework for data aggregation modeled on the concept of data processing pipelines. Documents enter a multi-stage pipeline that transforms the documents into an aggregated results.




回答2:


It would be better to match first and then group, so that you system only perform group operation on filtered records. If you perform group operation first then system will perform group on all records and then selects the records with memberId=61.

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



回答3:


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

would work if you are summing data which is not a part of array, if you want to sum the data present in some array in a document then use

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
})

and will get result like this

{
    "result" : [
        {
            "_id" : "someFieldvalue",
            "total" : someValue
        },
        {
            "_id" : "someOtherFieldvalue",
            "total" : someValue
        }
    ],
    "ok" : 1
}


来源:https://stackoverflow.com/questions/23094954/mongodb-sum-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!