- 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 of ratings in array and then include the field to original document in MongoDB?
You can use $avg operator along with aggregate framework. Let us first create a collection with documents −
> db.averageOfRatingsInArrayDemo.insertOne( ... { ... "StudentDetails":[ ... { ... "StudentId":1, ... "StudentScore":45 ... }, ... { ... "StudentId":2, ... "StudentScore":58 ... }, ... { ... "StudentId":3, ... "StudentScore":67 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd427dc2cba06f46efe9ee4") }
Following is the query to display all documents from a collection with the help of find() method −
> db.averageOfRatingsInArrayDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd427dc2cba06f46efe9ee4"), "StudentDetails" : [ { "StudentId" : 1, "StudentScore" : 45 }, { "StudentId" : 2, "StudentScore" : 58 }, { "StudentId" : 3, "StudentScore" : 67 } ] }
Following is the query to calculate average of ratings in array and then include field to original document in MongoDB −
> db.averageOfRatingsInArrayDemo.aggregate([ {$addFields : {StudentScoreAverage : {$avg : "$StudentDetails.StudentScore"}}} ]);
This will produce the following output −
{ "_id" : ObjectId("5cd427dc2cba06f46efe9ee4"), "StudentDetails" : [ { "StudentId" : 1, "StudentScore" : 45 }, { "StudentId" : 2, "StudentScore" : 58 }, { "StudentId" : 3, "StudentScore" : 67 } ], "StudentScoreAverage" : 56.666666666666664 }
Advertisements