MongoDB Aggregation
MongoDB $avg Operator
Photo Credit to CodeToFun
🙋 Introduction
In MongoDB's aggregation framework, the $avg
operator emerges as a fundamental tool for computing the average of numerical values within a dataset. This operator facilitates various statistical analyses and provides valuable insights into the central tendency of the data.
Let's explore how the $avg
operator can be effectively utilized within MongoDB's aggregation pipelines.
💡 Syntax
The syntax for the $avg
method is straightforward:
{ $avg: <expression> }
- $avg: This operator signifies that the subsequent operation will compute the average value.
- <expression>: This represents the expression that evaluates to the values for which the average will be computed. It could be a field reference, a mathematical expression, or a value.
📝 Example
⌨️ Input
Consider a collection named scores containing documents with fields student and score, representing student scores. Here are sample documents from the scores collection:
[
{ "_id": ObjectId("609c26812e9274a86871bc6a"), "student": "Alice", "score": 85 },
{ "_id": ObjectId("609c26812e9274a86871bc6b"), "student": "Bob", "score": 75 },
{ "_id": ObjectId("609c26812e9274a86871bc6c"), "student": "Charlie", "score": 90 }
]
🔄 Aggregation
Suppose we want to calculate the average score of all students. Here's how you can achieve this using the $avg
operator:
db.scores.aggregate([
{
$group: {
_id: null,
averageScore: { $avg: "$score" }
}
}
])
🧩 Explanation
- $group: This stage groups all documents into a single group (since _id: null) and computes the average score within that group.
- $avg: Calculates the average value of the specified field, which in this case is the score.
When discussing how the above aggregation works:
- _id: null: Since we are grouping all documents into a single group, there is no specific grouping key, hence _id is represented as null.
- averageScore: 83.33333333333333: The average score is calculated by adding up all the scores (85 + 75 + 90 = 250) and dividing by the total number of documents (3). So, the average score is approximately 83.33.
💻 Output
Now, let's take a look at the output generated by the aggregation pipeline:
{ "_id": null, "averageScore": 83.33333333333333 }
📚 Use Cases
Performance Evaluation:
The
$avg
operator is useful for calculating average performance metrics, such as exam scores, sales figures, or website traffic.Data Comparison:
Averaging values allows for comparison across different groups or time periods, aiding in identifying trends or disparities.
Quality Control:
In manufacturing or production environments, computing averages helps monitor product quality or process efficiency over time.
🎉 Conclusion
The $avg
operator in MongoDB's aggregation framework provides a powerful mechanism for computing average values within datasets, enabling users to gain insights into the central tendency of their data. Whether you're analyzing student scores, sales data, or production metrics, mastering the usage of $avg
empowers you to efficiently compute averages and derive meaningful insights from your datasets.
With its intuitive syntax and diverse applications, the $avg
operator proves to be an invaluable asset for handling numerical data effectively within MongoDB. Incorporate it into your aggregation pipelines to unlock new dimensions of data analysis and gain deeper insights into your datasets.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (MongoDB $avg Operator), please comment here. I will help you immediately.