简体   繁体   English

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

[英]How can I get average of String Value in MongoDB aggregation

I wants to do average of price but getting NAN.我想做平均价格但得到 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" }
        }
    }
])

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM