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

MongoDB เรียงลำดับเอกสารอย่างไร? ทำความเข้าใจ $natural order และการจัดเรียงแบบกำหนดเอง

MongoDB จัดเก็บและส่งคืนเอกสารในลำดับตามการเขียนข้อมูล (Insertion Order) โดยค่าเริ่มต้น ใช้ operator $natural เพื่อควบคุมลำดับนี้

ลำดับธรรมชาติ ($natural order)

db.yourCollectionName.find().sort({ "$natural": 1 });  // 1 = เก่าสุดก่อน (ASC)
db.yourCollectionName.find().sort({ "$natural": -1 }); // -1 = ใหม่สุดก่อน (DESC)

ตัวอย่าง: สร้างข้อมูลทดสอบ

> db.orderDocsDemo.insertOne({"UserScore":87});
> db.orderDocsDemo.insertOne({"UserScore":98});
> db.orderDocsDemo.insertOne({"UserScore":99});
> db.orderDocsDemo.insertOne({"UserScore":67});
> db.orderDocsDemo.insertOne({"UserScore":78});
> db.orderDocsDemo.insertOne({"UserScore":91});
> db.orderDocsDemo.insertOne({"UserScore":86});

คำสั่ง find() โดยไม่ระบุ sort จะได้ลำดับตามที่ insert เข้าไป:

{ "_id" : ObjectId("..."), "UserScore" : 87 }
{ "_id" : ObjectId("..."), "UserScore" : 98 }
{ "_id" : ObjectId("..."), "UserScore" : 99 }
{ "_id" : ObjectId("..."), "UserScore" : 67 }
{ "_id" : ObjectId("..."), "UserScore" : 78 }
{ "_id" : ObjectId("..."), "UserScore" : 91 }
{ "_id" : ObjectId("..."), "UserScore" : 86 }

ใช้ sort({ "$natural": 1 }) ได้ลำดับเดียวกัน (ยืนยันว่าเป็นลำดับ insertion)

การจัดเรียงตามฟิลด์เฉพาะ (Custom Sort)

> db.orderDocsDemo.find().sort({ "UserScore": 1 }); // น้อยไปมาก (ASC)
{ "_id" : ..., "UserScore" : 67 }
{ "_id" : ..., "UserScore" : 78 }
{ "_id" : ..., "UserScore" : 86 }
{ "_id" : ..., "UserScore" : 87 }
{ "_id" : ..., "UserScore" : 91 }
{ "_id" : ..., "UserScore" : 98 }
{ "_id" : ..., "UserScore" : 99 }

สรุป

  • Default order: ตามลำดับการ insert ($natural)
  • $natural: 1 = เรียงจากเก่าสุดไปใหม่สุด
  • $natural: -1 = เรียงจากใหม่สุดไปเก่าสุด
  • Custom sort: ใช้ sort({ "fieldName": 1 หรือ -1 }) เพื่อเรียงตามค่าฟิลด์ที่ต้องการ