1

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

1 Answer 1

1

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" }
  }}
])
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I needed! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.