Clauric
Clauric

Reputation: 1886

MongoDB Average returning NULL

I'm using MongoDB to get the average value of a car's engine size. However, the aggregate Average function keeps returning NULL.

Part of the DB is as follows:

 { "_id" : 1, "car" : { "engineSize" : 1.5 }, "addresses" : [ "X", "A" ] } 

 { "_id" : 6, "car" : { "engineSize" : 1.5 }, "addresses" : [ "X" ] }

 { "_id" : 2, "car" : { "engineSize" : 1.3 } }

 { "_id" : 5, "car" : { "engineSize" : 1.4 } } 

 { "_id" : 3, "car" : { "engineSize" : 1 } }

The command I am using to check for the average is:

db.project.aggregate([{$group : {_id: null, Average: {$avg: "$engineSize"}}}])

However, when I run this, it returns:

 { "_id" : null, "Average" : null }

Any suggestions on how to get it to return the correct value (i.e. 1.24)?

Upvotes: 4

Views: 3163

Answers (1)

Ashh
Ashh

Reputation: 46441

You are aggregating on the wrong field. It must be

db.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "Average": {
        "$avg": "$car.engineSize"
      }
    }
  }
])

Upvotes: 3

Related Questions