简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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