Aggregation Pipeline-এ $group এবং $addToSet ব্যবহার করে গ্রুপিং ও ইউনিক ভ্যালু সংগ্রহ
MongoDB-এ একই এগ্রিগেশন কোয়েরিতে গ্রুপিং এবং ডিস্টিনেক্ট (অনন্য) মান পেতে $group স্টেজের ভেতরে $addToSet অ্যাকিউমুলেটর ব্যবহার করা হয়। এটি অটোমেটিক্যালি ডুপ্লিকেট মান বাদ দিয়ে শুধু ইউনিক মানগুলো সংগ্রহ করে।
১. কালেকশন ও নমুনা ডেটা তৈরি
> db.demo16.insertOne({
"StudentName" : "Chris",
"StudentSection" : "A",
"StudentAge" : 23,
"StudentMarks" : 47
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e13827455d0fc6657d21f07") }
> db.demo16.insertOne({
"StudentName" : "Bob",
"StudentSection" : "B",
"StudentAge" : 21,
"StudentMarks" : 85
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e13827555d0fc6657d21f08") }
> db.demo16.insertOne({
"StudentName" : "Carol",
"StudentSection" : "A",
"StudentAge" : 26,
"StudentMarks" : 97
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e13827655d0fc6657d21f09") }
২. সব ডকুমেন্ট দেখানো
> db.demo16.find().pretty();
আউটপুট:
{
"_id" : ObjectId("5e13827455d0fc6657d21f07"),
"StudentName" : "Chris",
"StudentSection" : "A",
"StudentAge" : 23,
"StudentMarks" : 47
}
{
"_id" : ObjectId("5e13827555d0fc6657d21f08"),
"StudentName" : "Bob",
"StudentSection" : "B",
"StudentAge" : 21,
"StudentMarks" : 85
}
{
"_id" : ObjectId("5e13827655d0fc6657d21f09"),
"StudentName" : "Carol",
"StudentSection" : "A",
"StudentAge" : 26,
"StudentMarks" : 97
}
৩. গ্রুপ এবং ডিস্টিনেক্ট একসাথে করার এগ্রিগেশন কোয়েরি
> db.demo16.aggregate([{
$group : {
_id : null,
StudentName : { $addToSet : "$StudentName" },
StudentSection : { $addToSet : "$StudentSection" },
StudentMinimumAge : { $min : "$StudentAge" },
StudentMaximumAge : { $max : "$StudentAge" },
StudentMinimumMarks: { $min : "$StudentMarks" },
StudentMaximumMarks : { $max : "$StudentMarks" }
}
}]).pretty();
ব্যাখ্যা:
_id: null- সব ডকুমেন্টকে একসাথে গ্রুপ করতে।$addToSet- শুধু ইউনিক (ডুপ্লিকেট-বর্জিত) মানগুলো অ্যারে-তে সংগ্রহ করে।$min/$max- ন্যূনতম ও সর্বোচ্চ মান বের করতে।
৪. ফলাফল
{
"_id" : null,
"StudentName" : [ "Carol", "Bob", "Chris" ],
"StudentSection" : [ "B", "A" ],
"StudentMinimumAge" : 21,
"StudentMaximumAge" : 26,
"StudentMinimumMarks" : 47,
"StudentMaximumMarks" : 97
}
এখানে StudentName ও StudentSection ফিল্ডগুলোর ইউনিক মানগুলো অ্যারে হিসেবে পাওয়া গেছে, এবং বয়স ও নম্বরের মিন/ম্যাক্স মানও পাওয়া গেছে।