ใช้การรวมกลุ่ม ($group) ใน MongoDB aggregation pipeline เพื่อทำ group และ distinct พร้อมกัน ให้สร้างคอลเลกชันตัวอย่าง:
> 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();
คิวรี aggregation สำหรับ group และ distinct พร้อมกัน:
> 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, "StudentName" : [ "Carol", "Bob", "Chris" ], "StudentSection" : [ "B", "A" ], "StudentMinimumAge" : 21, "StudentMaximumAge" : 26, "StudentMinimumMarks" : 47, "StudentMaximumMarks" : 97 }
คำอธิบายโอเปอเรเตอร์
$addToSet: เพิ่มค่าลงในอาร์เรย์โดยไม่ซ้ำ (distinct)$min/$max: หาค่าต่ำสุด/สูงสุด_id: null: รวมกลุ่มทั้งหมดในคอลเลกชันเป็นกลุ่มเดียว