Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

db.collection.aggregate([
    {
        "$group": {
            "_id": "$item",
            "average": { "$avg": "$price" }
        }
    }
])

>Solution :

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
        ]
      }
    }
  }
])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading