![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
How to calculate average of a particular field in MongoDB?
To calculate average of a particular field, use aggregate() along with $avg. Let us create a collection with documents −
> db.demo214.insertOne({"Marks":56,"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3e319403d395bdc2134705") } > db.demo214.insertOne({"Marks":86,"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3e319c03d395bdc2134706") } > db.demo214.insertOne({"Marks":78,"Name":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3e31a403d395bdc2134707") }
Display all documents from a collection with the help of find() method −
> db.demo214.find();
This will produce the following output −
{ "_id" : ObjectId("5e3e319403d395bdc2134705"), "Marks" : 56, "Name" : "David" } { "_id" : ObjectId("5e3e319c03d395bdc2134706"), "Marks" : 86, "Name" : "Bob" } { "_id" : ObjectId("5e3e31a403d395bdc2134707"), "Marks" : 78, "Name" : "Carol" }
Following is the query to calculate average of a particular field in MongoDB −
> db.demo214.aggregate( ... [ ... { ... $group: ... { ... ... "_id":"_id", ... AverageValue: { $avg: "$Marks" } ... } ... } ... ] ...)
This will produce the following output
{ "_id" : "_id", "AverageValue" : 73.33333333333333 }
Advertisements