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 }