[英]How can I get average of String Value in MongoDB aggregation
我想做平均價格但得到 NAN。
這是示例數據:
{ "_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" }
我正在嘗試這段代碼:
db.collection.aggregate([
{
"$group": {
"_id": "$item",
"average": { "$avg": "$price" }
}
}
])
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
]
}
}
}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.