Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

เรียงลำดับและจัดกลุ่มในคิวรี่ Aggregate เดียวใน MongoDB

ใช้ $group ร่วมกับ $sort ใน Aggregate Pipeline เพื่อจัดกลุ่มและเรียงลำดับในคิวรี่เดียว เริ่มต้นด้วยการสร้างคอลเลกชันตัวอย่าง:

> db.sortAndGroupDemo.insertOne({ Price :40, Product: 10 });
{ "acknowledged" : true, "insertedId" : ObjectId("5ce8f2bc78f00858fb12e907") }
> db.sortAndGroupDemo.insertOne({ Price :100, Product: 10 });
{ "acknowledged" : true, "insertedId" : ObjectId("5ce8f2bc78f00858fb12e908") }
> db.sortAndGroupDemo.insertOne({ Price :90, Product: 20 });
{ "acknowledged" : true, "insertedId" : ObjectId("5ce8f2bc78f00858fb12e909") }
> db.sortAndGroupDemo.insertOne({ Price :200, Product: 10 });
{ "acknowledged" : true, "insertedId" : ObjectId("5ce8f2bc78f00858fb12e90a") }
> db.sortAndGroupDemo.insertOne({ Price :70, Product: 20 });
{ "acknowledged" : true, "insertedId" : ObjectId("5ce8f2bc78f00858fb12e90b") }
> db.sortAndGroupDemo.insertOne({ Price :70, Product: 30 });
{ "acknowledged" : true, "insertedId" : ObjectId("5ce8f2bd78f00858fb12e90c") }

แสดงเอกสาร:

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

คิวรี่ Aggregate จัดกลุ่มตาม Product แล้วเรียงตาม Product (ไม่ได้เรียงตาม Price เพราะ Price ถูก grouped แล้ว):

> db.sortAndGroupDemo.aggregate([
  { "$group": { "_id": "$Product" }},
  { "$sort" : { "_id": 1 }},
  { "$project": {"_id":1 }}
]);

คำอธิบาย:

  • $group: {_id: "$Product"} - จัดกลุ่มตามค่า Product (10, 20, 30)
  • $sort: {_id: 1} - เรียงกลุ่มตาม _id (Product) ขึ้น冇
  • $project: {_id: 1} - แสดงเฉพาะ _id (Product)

หมายเหตุ: หลัง $group แล้ว ฟิลด์ Price เดิมจะหายไป (ถ้าไม่ได้รวมไว้ใน $group) ดังนั้น $sort ต้องใช้ฟิลด์ที่มีอยู่หลัง $group (เช่น _id หรือฟิลด์ที่คำนวณได้)