MongoDB-তে অগ리게শন ফ্রেমওয়ার্ক ব্যবহার করে সাব-অ্যারে থেকে সর্বোচ্চ মান বের করা
MongoDB ডকুমেন্টের নেস্টেড অ্যারে (সাব-অ্যারে) থেকে সর্বোচ্চ মান বের করতে অগ리게শন পাইপলাইন ব্যবহার করতে হয়।
ধাপ ১: ডকুমেন্টসহ কালেকশন তৈরি করুন
> db.findHighestValueDemo.insertOne(
{
_id: 10001,
"StudentDetails": [
{ "StudentName": "Chris", "StudentMathScore": 56},
{ "StudentName": "Robert", "StudentMathScore": 47 },
{ "StudentName": "John", "StudentMathScore": 98 }
]
}
);
{ "acknowledged" : true, "insertedId" : 10001 }
> db.findHighestValueDemo.insertOne(
{
_id: 10002,
"StudentDetails": [
{ "StudentName": "Ramit", "StudentMathScore": 89},
{ "StudentName": "David", "StudentMathScore": 76 },
{ "StudentName": "Bob", "StudentMathScore": 97 }
]
}
);
{ "acknowledged" : true, "insertedId" : 10002 }
ধাপ ২: সব ডকুমেন্ট প্রদর্শন করুন
> db.findHighestValueDemo.find().pretty();
আউটপুট:
{
"_id" : 10001,
"StudentDetails" : [
{ "StudentName" : "Chris", "StudentMathScore" : 56 },
{ "StudentName" : "Robert", "StudentMathScore" : 47 },
{ "StudentName" : "John", "StudentMathScore" : 98 }
]
}
{
"_id" : 10002,
"StudentDetails" : [
{ "StudentName" : "Ramit", "StudentMathScore" : 89 },
{ "StudentName" : "David", "StudentMathScore" : 76 },
{ "StudentName" : "Bob", "StudentMathScore" : 97 }
]
}
ধাপ ৩: অগ리게শন পাইপলাইন দিয়ে সর্বোচ্চ মান বের করুন
> db.findHighestValueDemo.aggregate([
{$project: {"StudentDetails.StudentName":1, "StudentDetails.StudentMathScore":1}},
{$unwind: "$StudentDetails"},
{$sort: {"StudentDetails.StudentMathScore": -1}},
{$limit: 1}
]).pretty();
ফলাফল:
{
"_id" : 10001,
"StudentDetails" : {
"StudentName" : "John",
"StudentMathScore" : 98
}
}
পাইপলাইন ব্যাখ্যা:
- $project: শুধু প্রয়োজনীয় ফিল্ডগুলো (StudentName, StudentMathScore) রাখা হয়েছে
- $unwind: StudentDetails অ্যারেটি ফ্ল্যাটেন করা হয়েছে (প্রতিটি এলিমেন্ট আলাদা ডকুমেন্ট বنى)
- $sort: StudentMathScore অনুযায়ী ডিসেন্ডিং অর্ডারে (-1) সর্ট করা হয়েছে
- $limit: 1 - শুধু প্রথম (সর্বোচ্চ) ডকুমেন্টটি রাখা হয়েছে
ফলাফল: সব ডকুমেন্টের সাব-অ্যারে মিলিয়ে সর্বোচ্চ Math Score ৯৮ পাওয়া গেছে, যা John-এর।