Home > database >  How to get the average of an array and round the result in MongoDB
How to get the average of an array and round the result in MongoDB

Time:12-20

I want to get the average result rounded to 2 decimal places but my code is not working and I couldn't find any way to solve it.

db.customers.aggregate([
{
    $group: {
      _id: "$customer.gender",
      "average age": {
        $avg: {
          $round: [
            "$customer.age",
            2
          ]
        }
      }
    }
}])

CodePudding user response:

Your code works fine. Unless you have different data structure or different input.

db.collection.aggregate([
  {
    $group: {
      _id: "$customer.gender",
      "average age": {
        $avg: {
          $round: [
            "$customer.age",
            2
          ]
        }
      }
    }
  }
])

mongoplayground

CodePudding user response:

Age has no decimal digits, so i guess you want to round the average after the grouping like bellow, that uses the stage operator $set to add the new field. ($set=$addFields)

db.customers.aggregate([
  {
    $group: {
      _id: "$customer.gender",
      "average age": {
        $avg: "$customer.age"
      }
    }
  },
  {
    "$set": {
      "average age": {
        "$round": [
          "$average age",
          2
        ]
      }
    }
  }
])
  • Related