MongoDB-এ aggregate() ব্যবহার করে দেশ, রাজ্য ও সিটি অনুযায়ী গ্রুপিং
এগ리게েশন অপারেশন একাধিক ডকুমেন্ট থেকে মান গ্রুপ করে এবং গ্রুপ করা ডেটার ওপর বিভিন্ন অপারেশন চালিয়ে একটি ফলাফল রিটার্ন করে।
উদাহরণ: ডকুমেন্ট সহ কালেকশন তৈরি
> db.demo620.insertOne({"Country":"IND","City":"Delhi",state:"Delhi"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9a8de96c954c74be91e6a1") }
> db.demo620.insertOne({"Country":"IND","City":"Bangalore",state:"Karnataka"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9a8e336c954c74be91e6a3") }
> db.demo620.insertOne({"Country":"IND","City":"Mumbai",state:"Maharashtra"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9a8e636c954c74be91e6a4") }
সকল ডকুমেন্ট প্রদর্শন
> db.demo620.find();
আউটপুট
{ "_id" : ObjectId("5e9a8de96c954c74be91e6a1"), "Country" : "IND", "City" : "Delhi", "state" : "Delhi" }
{ "_id" : ObjectId("5e9a8e336c954c74be91e6a3"), "Country" : "IND", "City" : "Bangalore", "state" : "Karnataka" }
{ "_id" : ObjectId("5e9a8e636c954c74be91e6a4"), "Country" : "IND", "City" : "Mumbai", "state" : "Maharashtra" }
দেশ, রাজ্য ও সিটি অনুযায়ী এগ리게েট করার কুয়েরি
> db.demo620.aggregate([
... {
... "$group": {
... "_id": {
... "Country": "$Country",
... "state": "$state"
... },
... "City": {
... "$addToSet": {
... "City": "$City"
... }
... }
... }
... },
... {
... "$group": {
... "_id": "$_id.Country",
... "states": {
... "$addToSet": {
... "state": "$_id.state",
... "City": "$City"
... }
... }
... }
... }
... ]).pretty();
ফলাফল
{
"_id" : "IND",
"states" : [
{
"state" : "Delhi",
"City" : [
{
"City" : "Delhi"
}
]
},
{
"state" : "Maharashtra",
"City" : [
{
"City" : "Mumbai"
}
]
},
{
"state" : "Karnataka",
"City" : [
{
"City" : "Bangalore"
}
]
}
]
}