GeJN
GeJN

Reputation: 69

Mongodb aggregate, object sum inside object

I'm trying to agregate data in mongoDb. This request perfectly works:

db.getCollection('map').aggregate([
{
    $group: {
        _id: "$Support",
        gross: { $sum :"$Budget.Gross"},
    }}        
])

But, I'd prefere to have something like:

db.getCollection('map').aggregate([
{
    $group: {
        _id: "$Support",
        Budget: { gross: { $sum :"$Budget.Gross"}},
    }}        
])

Which doesn't work, saying: "The field 'Budget' must me an accumulator object". I understand why it is not possible to do it in that way. MongoDb doesn't know how to agregate { gross: { $sum :"$Budget.Gross"}}.

But, is there any way to obtain such a result ?

Thank you for your help

Upvotes: 1

Views: 182

Answers (1)

Ashh
Ashh

Reputation: 46451

You have to use $projection to reshape the the output accordingly

db.getCollection('map').aggregate([
  { "$group": {
    "_id": "$Support",
    "gross": { "$sum": "$Budget.Gross" },
  }},
  { "$project": {
    "Budget": { "gross": "$gross" }
  }}
])

Upvotes: 1

Related Questions