'How can I get average of String Value in MongoDB aggregation
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" }
}
}
])
Solution 1:[1]
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
]
}
}
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gibbs |
