Get Off My Lawn
Get Off My Lawn

Reputation: 36289

MongoDB sum() data

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

Upvotes: 1

Views: 504

Answers (3)

Saheed Hussain
Saheed Hussain

Reputation: 1158

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
}

Upvotes: 0

mark-cs
mark-cs

Reputation: 4707

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.

Upvotes: 4

Tayyab
Tayyab

Reputation: 10621

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

Upvotes: 1

Related Questions