- 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
Calculate average value in MongoDB
To calculate average value in MongoDB, use aggregate() along with $avg. Let us create a collection with documents −
> db.demo159.insertOne({"Score":50}); { "acknowledged" : true, "insertedId" : ObjectId("5e3557b2fdf09dd6d0853a01") } > db.demo159.insertOne({"Score":70}); { "acknowledged" : true, "insertedId" : ObjectId("5e3557b6fdf09dd6d0853a02") } > db.demo159.insertOne({"Score":60}); { "acknowledged" : true, "insertedId" : ObjectId("5e3557c4fdf09dd6d0853a03") }
Display all documents from a collection with the help of find() method −
> db.demo159.find();
This will produce the following output −
{ "_id" : ObjectId("5e3557b2fdf09dd6d0853a01"), "Score" : 50 } { "_id" : ObjectId("5e3557b6fdf09dd6d0853a02"), "Score" : 70 } { "_id" : ObjectId("5e3557c4fdf09dd6d0853a03"), "Score" : 60 }
Following is the query to calculate $avg value −
> db.demo159.aggregate([{$group: {_id:null, AverageValue: {$avg:"$Score"} } }])
This will produce the following output −
{ "_id" : null, "AverageValue" : 60 }
Advertisements