- 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
Calculating average value per document with sort in MongoDB?
To calculate average, use aggregate along with $avg. Let us first create a collection with documents −
> db.calculateAverage.insertOne({'Value':[10,20,80]}); { "acknowledged" : true, "insertedId" : ObjectId("5e0383e3f5e889d7a51994dc") } > db.calculateAverage.insertOne({'Value':[12,15,16]}); { "acknowledged" : true, "insertedId" : ObjectId("5e0383edf5e889d7a51994dd") } > db.calculateAverage.insertOne({'Value':[30,35,40]}); { "acknowledged" : true, "insertedId" : ObjectId("5e0383f5f5e889d7a51994de") }
Following is the query to display all documents from a collection with the help of find() method −
> db.calculateAverage.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e0383e3f5e889d7a51994dc"), "Value" : [ 10, 20, 80 ] } { "_id" : ObjectId("5e0383edf5e889d7a51994dd"), "Value" : [ 12, 15, 16 ] } { "_id" : ObjectId("5e0383f5f5e889d7a51994de"), "Value" : [ 30, 35, 40 ] }
Following is the query to calculate average value per document with sort −
> db.calculateAverage.aggregate([ { "$addFields": { "calavg": { "$avg": "$Value" } }}, { "$sort": { "calavg": 1 } } ],function(err, out) { res.send(out) });
This will produce the following output −
{ "_id" : ObjectId("5e0383edf5e889d7a51994dd"), "Value" : [ 12, 15, 16 ], "calavg" : 14.333333333333334 } { "_id" : ObjectId("5e0383f5f5e889d7a51994de"), "Value" : [ 30, 35, 40 ], "calavg" : 35 } { "_id" : ObjectId("5e0383e3f5e889d7a51994dc"), "Value" : [ 10, 20, 80 ], "calavg" : 36.666666666666664 }
Advertisements