Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to get average in aggregation of array element?
To calculate the average of array elements in MongoDB, use the $avg operator in an aggregation pipeline. This operator computes the arithmetic mean of all numeric values in an array field.
Syntax
db.collection.aggregate([
{ $project: { fieldName: { $avg: "$arrayField" } } }
])
Sample Data
Let us create a collection with documents containing an array of marks ?
db.demo584.insertOne({
"Marks": [75, 50, 85, 60, 80]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e91d827fd2d90c177b5bcc2")
}
Display all documents from the collection ?
db.demo584.find().pretty();
{
"_id": ObjectId("5e91d827fd2d90c177b5bcc2"),
"Marks": [
75,
50,
85,
60,
80
]
}
Example
Calculate the average of array elements using aggregation ?
db.demo584.aggregate([
{ $project: { MarksAvg: { $avg: "$Marks" } } }
]);
{ "_id": ObjectId("5e91d827fd2d90c177b5bcc2"), "MarksAvg": 70 }
Key Points
- The
$avgoperator calculates the arithmetic mean of numeric array elements - Non-numeric values in the array are ignored during calculation
- Use
$projectstage to create a new field containing the average value
Conclusion
The $avg operator in MongoDB aggregation pipelines efficiently calculates the average of array elements. It automatically handles numeric conversion and ignores non-numeric values, making it ideal for statistical calculations on array data.
Advertisements
