I wants to do average of price but getting NAN.
Here's Sample data:
{ "_id" : 1, "item" : "Item 1", "price" : "10" }
{ "_id" : 2, "item" : "Item 2", "price" : "20" }
{ "_id" : 3, "item" : "Item 1", "price" : "5" }
{ "_id" : 4, "item" : "Item 2", "price" : "10" }
{ "_id" : 5, "item" : "Item 1", "price" : "5" }
I am trying this code:
db.collection.aggregate([
{
"$group": {
"_id": "$item",
"average": { "$avg": "$price" }
}
}
])
CodePudding user response:
db.collection.aggregate([
{
"$group": {
"_id": "$item",
"average": {
"$avg": {
$toDecimal: "$price" //If price has decimals, it has higher precision than toDouble
}
}
}
},
{
$project: {
_id: 1,
avg: {
$round: [ //You can decide your precision
"$average",
1
]
}
}
}
])