MongoDB-এ সাব-ডকুমেন্ট (এমবেডেড ডকুমেন্ট) এর ফিল্ড অনুযায়ী ডকুমেন্ট সর্ট করতে অগ্রিগেশন পাইপলাইনে $unwind, $match, $sort ব্যবহার করা হয়।
নমুনা ডেটা তৈরি করা
sortBySubDocumentsDemo কালেকশনে দুটি ডকুমেন্ট ইনসার্ট করি যাতে StudentDetails অ্যারেতে প্রতিটি অবজেক্টে Age এবং StudentScore থাকে।
> db.sortBySubDocumentsDemo.insertOne(
{
"StudentName": "Chris",
"StudentDetails": [
{ "Age":21, "StudentScore":91 },
{ "Age":22, "StudentScore":99 },
{ "Age":21, "StudentScore":93 }
]
}
);
{ "acknowledged" : true, "insertedId" : ObjectId("5cd57e297924bb85b3f48942") }
> db.sortBySubDocumentsDemo.insertOne(
{
"StudentName": "Robert",
"StudentDetails": [
{ "Age":24, "StudentScore":78 },
{ "Age":21, "StudentScore":86 },
{ "Age":23, "StudentScore":45 }
]
}
);
{ "acknowledged" : true, "insertedId" : ObjectId("5cd57e4c7924bb85b3f48943") }
সকল ডকুমেন্ট দেখানো
> db.sortBySubDocumentsDemo.find().pretty();
আউটপুট:
{ "_id" : ObjectId("5cd57e297924bb85b3f48942"), "StudentName" : "Chris", "StudentDetails" : [ { "Age" : 21, "StudentScore" : 91 }, { "Age" : 22, "StudentScore" : 99 }, { "Age" : 21, "StudentScore" : 93 } ] }
{ "_id" : ObjectId("5cd57e4c7924bb85b3f48943"), "StudentName" : "Robert", "StudentDetails" : [ { "Age" : 24, "StudentScore" : 78 }, { "Age" : 21, "StudentScore" : 86 }, { "Age" : 23, "StudentScore" : 45 } ] }
অগ্রিগেশন দিয়ে সাব-ডকুমেন্ট ম্যাচ করে সর্ট করা
এই পাইপলাইন: ১) Age 21 가진 ডকুমেন্ট ফিল্টার, ২) StudentDetails আনউইন্ড, ৩) আবার Age 21 ফিল্টার, ৪) প্রজেক্ট, ৫) StudentScore অনুযায়ী অর্ডার, ৬) লিমিট ৫।
> db.sortBySubDocumentsDemo.aggregate([
{ $match: { 'StudentDetails.Age': 21 } },
{ $unwind: '$StudentDetails' },
{ $match: { 'StudentDetails.Age': 21 } },
{ $project: { _id: 0, "StudentName": 1, 'StudentDetails.StudentScore': 1 } },
{ $sort: { 'StudentDetails.StudentScore': 1 } },
{ $limit: 5 }
]);
আউটপুট:
{ "StudentName" : "Robert", "StudentDetails" : { "StudentScore" : 86 } }
{ "StudentName" : "Chris", "StudentDetails" : { "StudentScore" : 91 } }
{ "StudentName" : "Chris", "StudentDetails" : { "StudentScore" : 93 } }
নোট: $unwind অ্যারের প্রতিটি এলিমেন্টকে আলাদা ডকুমেন্ট বানায়, যাতে সর্ট করা যায়।