- 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
Get the average of marks in MongoDB with aggregate?
Use $avg operator along with aggregate framework. Let us first create a collection with documents. Here, one of the fields is StudentScore −
> db.averageReturiningNullDemo.insertOne( {"StudentDetails" : { "StudentScore" : 89 } }); { "acknowledged" : true, "insertedId" : ObjectId("5ce9822e78f00858fb12e927") } > db.averageReturiningNullDemo.insertOne( {"StudentDetails" : { "StudentScore" : 34 } }); { "acknowledged" : true, "insertedId" : ObjectId("5ce9822e78f00858fb12e928") } > db.averageReturiningNullDemo.insertOne( {"StudentDetails" : { "StudentScore" : 78 } }); { "acknowledged" : true, "insertedId" : ObjectId("5ce9822e78f00858fb12e929") }
Following is the query to display all documents from a collection with the help of find() method −
> db.averageReturiningNullDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ce9822e78f00858fb12e927"), "StudentDetails" : { "StudentScore" : 89 } } { "_id" : ObjectId("5ce9822e78f00858fb12e928"), "StudentDetails" : { "StudentScore" : 34 } } { "_id" : ObjectId("5ce9822e78f00858fb12e929"), "StudentDetails" : { "StudentScore" : 78 } }
Following is the query to average returning −
> db.averageReturiningNullDemo.aggregate([ { "$group": { "_id": null, "StudentScoreAverage": { "$avg": "$StudentDetails.StudentScore" } } } ]);
This will produce the following output −
{ "_id" : null, "StudentScoreAverage" : 67 }
Advertisements