gregooroo
gregooroo

Reputation: 168

Mongodb sum with distinct

Document structure

    {
        "_id": "5a21c5dff772de0555480ef5",
        "date": "2017-10-06T00:00:00.000Z",
        "amount": 1,
        "location": "Canada",
        "__v": 0
    }

I want to count amount for every location and in result have output similar to this:

{
  "location": "Canada",
  "amount": 8
}

Please give me some hints how to build a aggregate query for this (or maybe there is other way to do that).

Upvotes: 1

Views: 3699

Answers (1)

Joe
Joe

Reputation: 28376

This does sound like a job for aggregation.

Use the $group stage and $sum operator to combine your documents by location:

db.collection.aggregate([{$group:{_id:"$location", amount: {$sum: "$amount"}])

If you absolutely have to have the field be named 'location', use a $project stage to change '_id' to 'location':

db.collection.aggregate([
     {$group:{_id:"$location", amount: {$sum: "$amount"}}},
     {$project: {location: "$_id", amount:1, _id:0}}
])

Upvotes: 2

Related Questions