MongoDB sum() data

2019-08-05 16:48发布

问题:

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
}