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
Selected Reading
MongoDB query to get average in aggregation of array element?
To get an average of array elements, use $avg. Let us create a collection with documents −
> db.demo584.insertOne({"Marks":[75,50,85,60,80]});{
"acknowledged" : true,
"insertedId" : ObjectId("5e91d827fd2d90c177b5bcc2")
}
Display all documents from a collection with the help of find() method −
> db.demo584.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e91d827fd2d90c177b5bcc2"),
"Marks" : [
75,
50,
85,
60,
80
]
}
Following is the query to find avg in the aggregation of array element −
> db.demo584.aggregate([
... { $project: { MarksAvg: { $avg: "$Marks"} } }
... ])
This will produce the following output −
{ "_id" : ObjectId("5e91d827fd2d90c177b5bcc2"), "MarksAvg" : 70 } Advertisements
