如何在 MongoDB 聚合中获取字符串值的平均值

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

playground

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