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
]
}
}
}
}
])
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
]
}
}
}
])