MongoDB-এ ডুপ্লিকেট নামের ডকুমেন্টগুলো গ্রুপ করে প্রতিটি নামের জন্য সর্বোচ্চ (maximum) স্কোর বের করতে group() কমান্ড (লিগেসি) ব্যবহার করা হয়েছে। আধুনিক ভার্সনে aggregate() مع $max প্রস্তাবিত।
কলেকশন এবং ডকুমেন্ট তৈরি
> db.demo114.insertOne({"Score":60,"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2efc57d8f64a552dae6354") }
> db.demo114.insertOne({"Score":87,"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2efc5ad8f64a552dae6355") }
> db.demo114.insertOne({"Score":45,"Name":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2efc5dd8f64a552dae6356") }
> db.demo114.insertOne({"Score":67,"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2efc68d8f64a552dae6357") }
> db.demo114.insertOne({"Score":38,"Name":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2efc74d8f64a552dae6358") }
সব ডকুমেন্ট দেখানো
> db.demo114.find();
আউটপুট:
{ "_id" : ObjectId("5e2efc57d8f64a552dae6354"), "Score" : 60, "Name" : "Chris" }
{ "_id" : ObjectId("5e2efc5ad8f64a552dae6355"), "Score" : 87, "Name" : "Chris" }
{ "_id" : ObjectId("5e2efc5dd8f64a552dae6356"), "Score" : 45, "Name" : "David" }
{ "_id" : ObjectId("5e2efc68d8f64a552dae6357"), "Score" : 67, "Name" : "Chris" }
{ "_id" : ObjectId("5e2efc74d8f64a552dae6358"), "Score" : 38, "Name" : "David" }
লিগেসি group() কমান্ড দিয়ে সর্বোচ্চ স্কোর
> db.demo114.group(
... { key: { Name: true },
... reduce: function(c, p) {
... if (p.maximumScore < c.Score) {
... p.maximumScore = c.Score;
... }
... },
... initial: { maximumScore: 0 }
... });
ফলাফল
[ { "Name" : "Chris", "maximumScore" : 87 }, { "Name" : "David", "maximumScore" : 45 } ]
ব্যাখ্যা:
key: {Name: true}- Name ফিল্ড অনুযায়ী গ্রুপinitial: {maximumScore: 0}- প্রতিটি গ্রুপের জন্য ইনিশিয়াল ভ্যালুreduceফাংশন - প্রতিটি ডকুমেন্ট (c) গ্রুপ অ্যাকুমুলেটর (p) এ যোগ করুনp.maximumScore < c.Score- বর্তমান স্কোর বেশি হলে আপডেট
⚠️ গুরুত্বপূর্ণ সতর্কতা: db.collection.group() হলো লিগেসি (পুরানো) কমান্ড, বর্তমানে ডিপ্রিকেটেড। এটি শুধু শার্ডেড (sharded) কলেকশনে কাজ করে না এবং ১০,০০০ রেজাল্ট লিমিট আছে।
আধুনিক পদ্ধতি (Aggregate with $max) - প্রস্তাবিত:
db.demo114.aggregate([
{ $group: { _id: "$Name", maximumScore: { $max: "$Score" } } }
])
ফলাফল: {_id: "Chris", maximumScore: 87}, {_id: "David", maximumScore: 45}
অতিরিক্ত ফিল্ড রাখতে (first document):
db.demo114.aggregate([
{ $sort: { Score: -1 } },
{ $group: { _id: "$Name", maximumScore: { $first: "$Score" }, doc: { $first: "$$ROOT" } } },
{ $replaceRoot: { newRoot: "$doc" } }
])