Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Lấy N bản ghi cuối cùng trong MongoDB

Dùng sort({$natural:-1}) kết hợp limit() để lấy N bản ghi mới nhất (theo thứ tự chèn). Cú pháp:

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

Tạo collection getLastNRecordsDemo với 11 bản ghi (Maxwell, Carol, Bob, Sam, Robert, Mike, Chris, James, Jace, Ramit, David):

> db.getLastNRecordsDemo.insertOne({"EmployeeName":"Maxwell"});
... (thêm 10 bản ghi nữa) ...

Hiển thị tất cả (theo thứ tự chèn):

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

Lấy 7 bản ghi cuối (mới nhất):

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

Kết quả (từ David ngược lên Robert):