![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
Get the average of an entire field using the aggregation framework in MongoDB?
You can use aggregate() method for this. Let us first create a collection with documents
> db.averageAggregationDemo.insertOne({"PlayerGameScore":45}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ed66bd628fa4220163b95") } > db.averageAggregationDemo.insertOne({"PlayerGameScore":55}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ed671d628fa4220163b96") } > db.averageAggregationDemo.insertOne({"PlayerGameScore":65}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ed676d628fa4220163b97") } > db.averageAggregationDemo.insertOne({"PlayerGameScore":35}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ed67bd628fa4220163b98") } > db.averageAggregationDemo.insertOne({"PlayerGameScore":16}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ed701d628fa4220163b99") }
Following is the query to display all documents from a collection with the help of find() method
> db.averageAggregationDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c9ed66bd628fa4220163b95"), "PlayerGameScore" : 45 } { "_id" : ObjectId("5c9ed671d628fa4220163b96"), "PlayerGameScore" : 55 } { "_id" : ObjectId("5c9ed676d628fa4220163b97"), "PlayerGameScore" : 65 } { "_id" : ObjectId("5c9ed67bd628fa4220163b98"), "PlayerGameScore" : 35 } { "_id" : ObjectId("5c9ed701d628fa4220163b99"), "PlayerGameScore" : 16 } Following is the query to get the average of an entire field with aggregation: > db.averageAggregationDemo.aggregate({ "$group": { "_id": null, "PlayerGameScoreAverage": { "$avg": "$PlayerGameScore" } } } );
This will produce the following output
{ "_id" : null, "PlayerGameScoreAverage" : 43.2 }
Advertisements