MongoDB অগ্রিগেশন ফ্রেমওয়ার্কের $avg অপারেটর ব্যবহার করে অ্যারের সংখ্যাগুলোর গড় বের করা এবং সেটি ডকুমেন্টে নতুন ফিল্ড হিসেবে যোগ করা যায়।
নমুনা ডেটা তৈরি করা
averageOfRatingsInArrayDemo কালেকশনে একটি ডকুমেন্ট ইনসার্ট করি যাতে StudentDetails অ্যারেতে প্রতিটি অবজেক্টে StudentScore থাকে।
> 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 }
]
}
$avg দিয়ে গড় বের করে নতুন ফিল্ড যোগ করা
$addFields স্টেজে $avg ব্যবহার করে StudentScoreAverage ফিল্ড তৈরি করি:
> 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
}
টিপস: আপনি চাইলে $project দিয়ে শুধু নির্দিষ্ট ফিল্ডগুলো রিটার্ন করতে পারেন।