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

วิธี Get Last N Records ใน MongoDB (เรียงลำดับย้อนหลัง + limit)

ใช้ sort({$natural: -1}) เรียงตามลำดับการ Insert (Natural Order) ย้อนหลัง แล้ว limit(N) จำกัดจำนวน

ไวยากรณ์


db.yourCollectionName.find().sort({$natural: -1}).limit(yourValue);

สร้างข้อมูลตัวอย่าง (11 Documents)


> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Maxwell"});
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Carol"});
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Bob"});
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Sam"});
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Robert"});
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Mike"});
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Chris"});
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"James"});
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Jace"});
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Ramit"});
> db.getLastNRecordsDemo.insertOne({"EmployeeName":"David"});

แสดงเอกสารทั้งหมด (เรียงตาม Insert Order)


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

Get Last 7 Records


> db.getLastNRecordsDemo.find().sort({$natural: -1}).limit(7);

ผลลัพธ์ (7 รายการล่าสุด: David, Ramit, Jace, James, Chris, Mike, Robert)


{ "_id" : ObjectId("5c6ecf8d6fd07954a4890693"), "EmployeeName" : "David" }
{ "_id" : ObjectId("5c6ecf7d6fd07954a4890692"), "EmployeeName" : "Ramit" }
{ "_id" : ObjectId("5c6ecf756fd07954a4890691"), "EmployeeName" : "Jace" }
{ "_id" : ObjectId("5c6ecf6f6fd07954a4890690"), "EmployeeName" : "James" }
{ "_id" : ObjectId("5c6ecf686fd07954a489068f"), "EmployeeName" : "Chris" }
{ "_id" : ObjectId("5c6ecf606fd07954a489068e"), "EmployeeName" : "Mike" }
{ "_id" : ObjectId("5c6ecf596fd07954a489068d"), "EmployeeName" : "Robert" }

หมายเหตุ: $natural เรียงตาม Physical Order บน Disk (โดยประมาณ Insert Order) หากต้องการ Sort ตาม Field เฉพาะ (เช่น Timestamp) ใช้ sort({"createdAt": -1}) แทน จะแม่นยำกว่า