0

I have the following query:

[
  {
    "$group": {
      "_id": "$Region",
      "Total Sales": {
        "$sum": "$Sales"
      },
      "Average Sales": {
        "$avg": "$Sales"
      }
    }
  }
]

This returns the response in the following format:

[
  {
    "_id": "Canada",
    "Total Sales": 66928.17,
    "Average Sales": 174.292109375,
  }
  .....
]

How do I refactor the query to get a response in the following format:

[{
    "_id": "Canada",
    "Sales":{"Total":66928.17, "Average":174.292109375},
  }
  ......
]

So far I've tried like this but it doesn't work:

{
  "$group": {
    "_id": "$Region",
    "Sales": {
      "Total":{
          "$sum": "$Sales"
      },
      "Average":{
          "$avg": "$Sales"
      }
    }
  }
}

1 Answer 1

1

Use $project to decorate the output document(s).

db.collection.aggregate([
  {
    "$group": {
      "_id": "$Region",
      "total": {
        "$sum": "$Sales"
      },
      "average": {
        "$avg": "$Sales"
      }
    }
  },
  {
    $project: {
      "Sales": {
        "Total": "$total",
        "Average": "$average"
      }
    }
  }
])

Sample Mongo PLayground

Sign up to request clarification or add additional context in comments.

2 Comments

is it possible to achieve this in group stage itself so that we can query for multiple keys e.g Sum of Profit etc. $group would become very messy otherwise
No, for each field (except _id) in $group, must be accumulator. Use $project to decorate desired output.

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.