- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
- Related Articles
- Get the average of an entire field using the aggregation framework in MongoDB?
- MongoDB query to get record beginning with specific element from an array?
- MongoDB query to get array of nested string?
- MongoDB query to replace value with aggregation?
- MongoDB query to calculate average
- MongoDB query to slice only one element of array
- MongoDB Aggregation to slice array inside array
- MongoDB query to find property of first element of array?
- MongoDB query to add new array element in document
- MongoDB Aggregate to get average from document and of array elements?
- Sort and Group in one MongoDB aggregation query?
- Does aggregation query with $match works in MongoDB?
- MongoDB aggregation framework with group query example?
- MongoDB query to pull array element from a collection?
- MongoDB query to group several fields using aggregation framework?

Advertisements