Home > Software design >  MongoDB - How do I add multiple aggregations in query
MongoDB - How do I add multiple aggregations in query

Time:01-05

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

CodePudding user response:

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

  •  Tags:  
  • Related