Amanjot
Amanjot

Reputation: 2058

Getting Average in a collection in mongodb

I am new to MongoDB. I want to take average, max, min document value in a whole collection. I was able to calculate max and min but don't know how to calculate average or how to start it.

This is how I calculated max.

db.mytable.find({},{"abc":1}).sort({"abc":-1}).limit(1);

Upvotes: 2

Views: 2734

Answers (2)

chridam
chridam

Reputation: 103345

To get the average for the whole collection, use the aggregation framework with the $group pipeline operator where you can specify an _id value of null to calculate the accumulated average value for all the input documents as a whole:

db.mytable.aggregate([
    {
        "$group": { 
            "_id": null, 
            "avg": { "$avg": "$abc" } 
        }
    }
]);

Upvotes: 4

jabclab
jabclab

Reputation: 15042

You'll want to investigate the Aggregation Framework for this:

For the mean average you can use:

db.mytable.aggregate(
  [
    {
      $group: { _id: "$abc", avg: { $avg: "$to_average" } }
    }
  ]
);

You can also use the aggregation framework for max, e.g.

db.mytable.aggregate(
  [
    {
      $group: { _id: "$abc", max: { $max: "$to_get_max_for" } }
    }
  ]
);

Upvotes: 1

Related Questions