MongoDB Query to Calculate Average Using Aggregation
$group and $avg operators like this: db.collection.aggregate([{ $group: { _id: null, averageValue: { $avg: "$fieldName" } } }]) to calculate the average of a field.Examples
How to Think About It
$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
Code
db.scores.insertMany([{ score: 10 }, { score: 20 }, { score: 30 }]);
const result = db.scores.aggregate([
{ $group: { _id: null, averageScore: { $avg: "$score" } } }
]).toArray();
printjson(result);Dry Run
Let's trace the average calculation for scores 10, 20, and 30.
Group all documents
All documents are grouped together with _id: null.
Calculate average
Calculate average of scores: (10 + 20 + 30) / 3 = 20.
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
db.scores.mapReduce( function() { emit(1, this.score); }, function(key, values) { return Array.sum(values) / values.length; }, { out: { inline: 1 } } );
const scores = db.scores.find().toArray(); const avg = scores.reduce((sum, doc) => sum + doc.score, 0) / scores.length; print(avg);
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Aggregation with $avg | O(n) | O(1) | Large datasets, efficient server-side calculation |
| mapReduce | O(n) | O(n) | Complex custom calculations, less efficient |
| Application code calculation | O(n) | O(n) | Small datasets or when aggregation is not possible |
$group and $avg for efficient average calculations directly in MongoDB._id: null in $group causes MongoDB to group by each unique field value instead of calculating a single average.