কম্পিউটার টিউটোরিয়াল

MongoDB-এ গভীর নেস্টেড সাব-লিস্ট কনক্যাটেনেট করা

MongoDB-এ গভীর নেস্টেড অ্যারে (সাব-লিস্ট) থেকে ডেটা এক্সট্রাক্ট করে একটি ফ্ল্যাট অ্যারে তৈরি করতে অ্যাগ্রিগেশন পাইপলাইনে একাধিক $unwind স্টেজ ব্যবহার করা হয়। তারপর সর্ট, লিমিট, এবং রিশেপ করা যায়।

নমুনা কালেকশন তৈরি (গভীর নেস্টেড স্ট্রাকচার)

> db.demo70.insertOne({
  "first": [
    { 
      "details": { 
        "second": [ 
          { "StudentDetails": { "Score": 10 } },
          { "StudentDetails": { "Score": 20 } },
          { "StudentDetails": { "Score": 30 } }
        ] 
      } 
    },
    { 
      "details": { 
        "second": [ 
          { "StudentDetails": { "Score": 11 } },
          { "StudentDetails": { "Score": 18 } },
          { "StudentDetails": { "Score": 29 } }
        ] 
      } 
    }
  ]
});
{ "acknowledged": true, "insertedId": ObjectId("5e29ad4d0912fae76b13d76d") }

ডকুমেন্ট দেখানো

> db.demo70.find().pretty();

স্ট্রাকচার: first[] → details → second[] → StudentDetails → Score

গভীর সাব-লিস্ট কনক্যাটেনেট এবং টপ ৩ স্কোর বের করা

> db.demo70.aggregate([
  { $unwind: "$first" },
  { $unwind: "$first.details.second" },
  { $sort: { "first.details.second.StudentDetails.Score": -1 } },
  { $limit: 3 },
  { $replaceRoot: { newRoot: "$first.details.second.StudentDetails" } },
  { $sort: { "Score": 1 } }
]);

ফলাফল

{ "Score": 20 }
{ "Score": 29 }
{ "Score": 30 }

ব্যাখ্যা:

  1. $unwind: "$first" - বাহ্যিক অ্যারে ফ্ল্যাটেন।
  2. $unwind: "$first.details.second" - নেস্টেড second অ্যারে ফ্ল্যাটেন।
  3. $sort: ... -1 - স্কোর ডিসেন্ডিং সর্ট (সর্বোচ্চ প্রথমে)।
  4. $limit: 3 - টপ ৩ রেকর্ড নেয়।
  5. $replaceRoot - ডকুমেন্টের রুট পরিবর্তন করে শুধু StudentDetails অবজেক্ট রাখে।
  6. $sort: { Score: 1 } - ফাইনাল আউটপুট অ্যাসেন্ডিং সর্ট।

সর্বোচ্চ ৩টি স্কোর: ৩০, ২৯, ২০ (অ্যাসেন্ডিং: ২০, ২৯, ৩০)।

সাব-লিস্ট কনক্যাটেনেট (সর্ট/লিমিট ছাড়া)

শুধু সব স্কোর একসাথে ফ্ল্যাট অ্যারেতে পেতে:

db.demo70.aggregate([
  { $unwind: "$first" },
  { $unwind: "$first.details.second" },
  { $replaceRoot: { newRoot: "$first.details.second.StudentDetails" } },
  { $group: { _id: null, AllScores: { $push: "$Score" } } }
]);

ফলাফল: { "_id": null, "AllScores": [ 10, 20, 30, 11, 18, 29 ] }

  1. MongoDB-এ _id দিয়ে গ্রুপ করে ডকুমেন্ট কাউন্ট করা

  2. MongoDB-এ কালেকশন রিনেম করা (renameCollection)

  3. MongoDB-তে এমবেডেড ডকুমেন্ট কোয়েরি করা (aggregate + $unwind)

  4. MongoDB-এ শর্তসাপেক্ষ কনক্যাটেনেশন (Concatenate with Condition)