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

Xác định document cuối cùng trong kết quả find() MongoDB

Để lấy document cuối cùng (theo thứ tự insert mặc định), sắp xếp giảm dần theo _id (vì ObjectId chứa timestamp) và lấy 1 document.

Cú pháp

db.collection.find().sort({ _id: -1 }).limit(1).pretty();

Ví dụ minh họa

Tạo collection identifyLastDocuementDemo chèn lần lượt 6 document:

> db.identifyLastDocuementDemo.insertOne({ "UserName": "Larry", "UserAge": 24, "UserCountryName": "US" });
> db.identifyLastDocuementDemo.insertOne({ "UserName": "Chris", "UserAge": 21, "UserCountryName": "UK" });
> db.identifyLastDocuementDemo.insertOne({ "UserName": "David", "UserAge": 25, "UserCountryName": "AUS" });
> db.identifyLastDocuementDemo.insertOne({ "UserName": "Sam", "UserAge": 26, "UserCountryName": "US" });
> db.identifyLastDocuementDemo.insertOne({ "UserName": "Mike", "UserAge": 27, "UserCountryName": "AUS" });
> db.identifyLastDocuementDemo.insertOne({ "UserName": "Carol", "UserAge": 28, "UserCountryName": "UK" });

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

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

Kết quả: Carol là document cuối cùng chèn vào.

{ "_id" : ObjectId("5c94a2ff..."), "UserName" : "Larry", ... }
{ "_id" : ObjectId("5c94a309..."), "UserName" : "Chris", ... }
{ "_id" : ObjectId("5c94a317..."), "UserName" : "David", ... }
{ "_id" : ObjectId("5c94a322..."), "UserName" : "Sam", ... }
{ "_id" : ObjectId("5c94a32e..."), "UserName" : "Mike", ... }
{ "_id" : ObjectId("5c94a33c..."), "UserName" : "Carol", ... }

Truy vấn document cuối cùng

> db.identifyLastDocuementDemo.find().sort({ _id: -1 }).limit(1).pretty();

Kết quả:

{ "_id" : ObjectId("5c94a33c4cf1f7a64fa4df5c"), "UserName" : "Carol", "UserAge" : 28, "UserCountryName" : "UK" }

Giải thích

  • _id (ObjectId) 4 byte đầu là timestamp (giây từ epoch). Sắp xếp _id: -1 tương đương sắp xếp theo thời gian tạo giảm dần.
  • limit(1) chỉ lấy 1 document đầu tiên sau khi sort.
  • Hiệu quả cao nhờ index mặc định trên _id.

Các trường hợp khác

  • Document cuối theo field khác: .sort({ createdAt: -1 }).limit(1) (cần index trên createdAt).
  • Lấy N document cuối: .sort({ _id: -1 }).limit(N).
  • Trong Aggregation: { $sort: { _id: -1 } }, { $limit: 1 }.
  • FindOneAndUpdate (atomic get last): db.coll.findOneAndUpdate({ _id: { $exists: true } }, {}, { sort: { _id: -1 } }).

Cảnh báo

Nếu collection có **sharded** hoặc **capped collection** với thứ tự tự nhiên khác, hãy dùng field timestamp tường minh (createdAt) thay vì _id.