เพื่อคิวรี่ Top N Rows ใน MongoDB ใช้ Aggregation Framework ร่วมกับ $sort และ $limit
ตัวอย่างการใช้งาน
สร้างคอลเลกชันพร้อมข้อมูลนักเรียนและคะแนน:
> db.topNRowsDemo.insertOne({"StudentName":"Larry","Score":78});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca26eee6304881c5ce84b91") }
> db.topNRowsDemo.insertOne({"StudentName":"Chris","Score":45});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca26ef66304881c5ce84b92") }
> db.topNRowsDemo.insertOne({"StudentName":"Mike","Score":65});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca26efe6304881c5ce84b93") }
> db.topNRowsDemo.insertOne({"StudentName":"Adam","Score":55});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca26f066304881c5ce84b94") }
> db.topNRowsDemo.insertOne({"StudentName":"John","Score":86});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca26f0f6304881c5ce84b95") }
แสดงเอกสารทั้งหมด:
> db.topNRowsDemo.find().pretty();
ผลลัพธ์:
{ "_id" : ObjectId("5ca26eee6304881c5ce84b91"), "StudentName" : "Larry", "Score" : 78 }
{ "_id" : ObjectId("5ca26ef66304881c5ce84b92"), "StudentName" : "Chris", "Score" : 45 }
{ "_id" : ObjectId("5ca26efe6304881c5ce84b93"), "StudentName" : "Mike", "Score" : 65 }
{ "_id" : ObjectId("5ca26f066304881c5ce84b94"), "StudentName" : "Adam", "Score" : 55 }
{ "_id" : ObjectId("5ca26f0f6304881c5ce84b95"), "StudentName" : "John", "Score" : 86 }
คิวรี่ Top N Rows (ที่นี่คือ Top 5 เรียงตามชื่อ แล้วกรองคะแนน > 65)
> db.topNRowsDemo.aggregate([
... {$sort: {StudentName: 1}},
... {$limit: 5},
... {$match: {Score: {$gt: 65}}}
... ]).pretty();
ผลลัพธ์ (นักเรียนที่ได้คะแนน > 65):
{ "_id" : ObjectId("5ca26f0f6304881c5ce84b95"), "StudentName" : "John", "Score" : 86 }
{ "_id" : ObjectId("5ca26eee6304881c5ce84b91"), "StudentName" : "Larry", "Score" : 78 }
สังเกต: ลำดับ Stage ใน Pipeline สำคัญมาก - ตัวอย่างนี้ เรียงชื่อก่อน จำกัด 5 รายการ แล้วค่อยกรองคะแนน > 65