आप कुल ढांचे के साथ $avg ऑपरेटर का उपयोग कर सकते हैं। आइए पहले दस्तावेजों के साथ एक संग्रह बनाएं -
> db.averageOfRatingsInArrayDemo.insertOne(
... {
... "StudentDetails":[
... {
... "StudentId":1,
... "StudentScore":45
... },
... {
... "StudentId":2,
... "StudentScore":58
... },
... {
... "StudentId":3,
... "StudentScore":67
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd427dc2cba06f46efe9ee4")
} खोज () विधि की मदद से संग्रह से सभी दस्तावेजों को प्रदर्शित करने के लिए क्वेरी निम्नलिखित है -
> db.averageOfRatingsInArrayDemo.find().pretty();
यह निम्नलिखित आउटपुट देगा -
{
"_id" : ObjectId("5cd427dc2cba06f46efe9ee4"),
"StudentDetails" : [
{
"StudentId" : 1,
"StudentScore" : 45
},
{
"StudentId" : 2,
"StudentScore" : 58
},
{
"StudentId" : 3,
"StudentScore" : 67
}
]
} सरणी में औसत रेटिंग की गणना करने के लिए क्वेरी निम्नलिखित है और फिर MongoDB में फ़ील्ड को मूल दस्तावेज़ में शामिल करें -
> db.averageOfRatingsInArrayDemo.aggregate([ {$addFields : {StudentScoreAverage : {$avg : "$StudentDetails.StudentScore"}}} ]); यह निम्नलिखित आउटपुट देगा -
{ "_id" : ObjectId("5cd427dc2cba06f46efe9ee4"), "StudentDetails" : [ { "StudentId" : 1, "StudentScore" : 45 }, { "StudentId" : 2, "StudentScore" : 58 }, { "StudentId" : 3, "StudentScore" : 67 } ], "StudentScoreAverage" : 56.666666666666664 }