0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Calculate Average Using Aggregation

Use the MongoDB aggregation pipeline with $group and $avg operators like this: db.collection.aggregate([{ $group: { _id: null, averageValue: { $avg: "$fieldName" } } }]) to calculate the average of a field.
📋

Examples

Input[{ score: 10 }, { score: 20 }, { score: 30 }]
Output[{ _id: null, averageValue: 20 }]
Input[{ price: 100 }, { price: 200 }, { price: 300 }, { price: 400 }]
Output[{ _id: null, averageValue: 250 }]
Input[]
Output[]
🧠

How to Think About It

To find the average of a field in MongoDB, you group all documents together using $group with _id: null to treat the whole collection as one group, then use $avg to calculate the average of the specified field across all documents.
📐

Algorithm

1
Select the collection to query.
2
Use the aggregation pipeline with a single stage: $group.
3
Set _id to null to group all documents together.
4
Use $avg operator on the target field to calculate the average.
5
Return the result with the average value.
💻

Code

mongodb
db.scores.insertMany([{ score: 10 }, { score: 20 }, { score: 30 }]);
const result = db.scores.aggregate([
  { $group: { _id: null, averageScore: { $avg: "$score" } } }
]).toArray();
printjson(result);
Output
[ { "_id" : null, "averageScore" : 20 } ]
🔍

Dry Run

Let's trace the average calculation for scores 10, 20, and 30.

1

Group all documents

All documents are grouped together with _id: null.

2

Calculate average

Calculate average of scores: (10 + 20 + 30) / 3 = 20.

3

Return result

Return [{ _id: null, averageScore: 20 }].

score
10
20
30
💡

Why This Works

Step 1: Grouping documents

Using $group with _id: null combines all documents into one group to calculate aggregate values.

Step 2: Calculating average

$avg operator computes the average of the specified field values within the group.

Step 3: Returning result

The aggregation returns a document with the average value under the specified key.

🔄

Alternative Approaches

Using mapReduce
mongodb
db.scores.mapReduce(
  function() { emit(1, this.score); },
  function(key, values) { return Array.sum(values) / values.length; },
  { out: { inline: 1 } }
);
mapReduce is more complex and slower than aggregation but can be used for custom calculations.
Calculating average in application code
mongodb
const scores = db.scores.find().toArray();
const avg = scores.reduce((sum, doc) => sum + doc.score, 0) / scores.length;
print(avg);
Fetching all data and calculating average in app code is less efficient for large datasets.

Complexity: O(n) time, O(1) space

Time Complexity

The aggregation scans all documents once, so time complexity is O(n) where n is the number of documents.

Space Complexity

Aggregation uses constant extra space O(1) as it only stores running totals for average calculation.

Which Approach is Fastest?

Aggregation with $avg is fastest and most efficient compared to mapReduce or client-side calculations.

ApproachTimeSpaceBest For
Aggregation with $avgO(n)O(1)Large datasets, efficient server-side calculation
mapReduceO(n)O(n)Complex custom calculations, less efficient
Application code calculationO(n)O(n)Small datasets or when aggregation is not possible
💡
Use the aggregation framework with $group and $avg for efficient average calculations directly in MongoDB.
⚠️
Forgetting to set _id: null in $group causes MongoDB to group by each unique field value instead of calculating a single average.