![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
Calculate the average value in a MongoDB document grouping by null?
You can use $group operator with _id: null. Following is the syntax −
db.yourCollectionName.aggregate([{$group: {_id:null, "anyFieldName": {$avg:"$yourFieldName"} } }]);
Let us first create a collection with documents −
> db.caculateTheAverageValueDemo.insertOne({"Population":100}); { "acknowledged" : true, "insertedId" : ObjectId("5cd68a197924bb85b3f4895f") } > db.caculateTheAverageValueDemo.insertOne({"Population":500}); { "acknowledged" : true, "insertedId" : ObjectId("5cd68a1c7924bb85b3f48960") } > db.caculateTheAverageValueDemo.insertOne({"Population":200}); { "acknowledged" : true, "insertedId" : ObjectId("5cd68a237924bb85b3f48961") } > db.caculateTheAverageValueDemo.insertOne({"Population":100}); { "acknowledged" : true, "insertedId" : ObjectId("5cd68a297924bb85b3f48962") } > db.caculateTheAverageValueDemo.insertOne({"Population":100}); { "acknowledged" : true, "insertedId" : ObjectId("5cd68a2e7924bb85b3f48963") }
Following is the query to display all documents from a collection with the help of find() method −
> db.caculateTheAverageValueDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd68a197924bb85b3f4895f"), "Population" : 100 } { "_id" : ObjectId("5cd68a1c7924bb85b3f48960"), "Population" : 500 } { "_id" : ObjectId("5cd68a237924bb85b3f48961"), "Population" : 200 } { "_id" : ObjectId("5cd68a297924bb85b3f48962"), "Population" : 100 } { "_id" : ObjectId("5cd68a2e7924bb85b3f48963"), "Population" : 100 }
Following is the query to average the values of a MongoDB document −
> db.caculateTheAverageValueDemo.aggregate([{$group: {_id:null, "AveragePopulation": {$avg:"$Population"} } }]);
This will produce the following output −
{ "_id" : null, "AveragePopulation" : 200 }
Advertisements