MongoDB sum() data

2019-08-05 16:27发布

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

3条回答
Evening l夕情丶
2楼-- · 2019-08-05 17:00

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.

查看更多
对你真心纯属浪费
3楼-- · 2019-08-05 17:07

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" } } }                       
)
查看更多
beautiful°
4楼-- · 2019-08-05 17:20
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
}
查看更多
登录 后发表回答