Để lấy document có _id lớn nhất (document mới nhất insert) trong MongoDB, bạn sắp xếp giảm dần theo _id và lấy 1 document đầu tiên.
Cú pháp
db.collection.find().sort({_id: -1}).limit(1)
Ví dụ minh họa
Tạo collection và dữ liệu
> db.getElementWithMaxIdDemo.insertOne({"Name":"John","Age":21});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8bbce480f10143d8431e1c") }
> db.getElementWithMaxIdDemo.insertOne({"Name":"Larry","Age":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8bbcec80f10143d8431e1d") }
> db.getElementWithMaxIdDemo.insertOne({"Name":"David","Age":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8bbcf580f10143d8431e1e") }
> db.getElementWithMaxIdDemo.insertOne({"Name":"Chris","Age":20});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8bbcfe80f10143d8431e1f") }
> db.getElementWithMaxIdDemo.insertOne({"Name":"Robert","Age":25});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8bbd0880f10143d8431e20") }
Xem tất cả documents
> db.getElementWithMaxIdDemo.find().pretty();
{
"_id" : ObjectId("5c8bbce480f10143d8431e1c"),
"Name" : "John",
"Age" : 21
}
{
"_id" : ObjectId("5c8bbcec80f10143d8431e1d"),
"Name" : "Larry",
"Age" : 24
}
{
"_id" : ObjectId("5c8bbcf580f10143d8431e1e"),
"Name" : "David",
"Age" : 23
}
{
"_id" : ObjectId("5c8bbcfe80f10143d8431e1f"),
"Name" : "Chris",
"Age" : 20
}
{
"_id" : ObjectId("5c8bbd0880f10143d8431e20"),
"Name" : "Robert",
"Age" : 25
}
Lấy document có _id lớn nhất
> db.getElementWithMaxIdDemo.find().sort({_id:-1}).limit(1).pretty()
{
"_id" : ObjectId("5c8bbd0880f10143d8431e20"),
"Name" : "Robert",
"Age" : 25
}
Tại sao sort theo _id cho document mới nhất?
ObjectId trong MongoDB bao gồm timestamp (4 byte đầu) + machine/process/counter. Do đó:
- ObjectId mới hơn → giá trị lớn hơn
- Sắp xếp
{_id: -1}= sắp xếp theo thời gian tạo giảm dần - Document đầu tiên sau sort = document insert gần nhất
Các cách khác
| Cách | Cú pháp | Ưu điểm |
|---|---|---|
| Sort + limit | find().sort({_id:-1}).limit(1) | Đơn giản, chuẩn |
| findOne + sort | findOne({}, {sort: {_id: -1}}) | Trả về object trực tiếp, không phải cursor |
| Aggregation | aggregate([{$sort:{_id:-1}}, {$limit:1}]) | Tích hợp trong pipeline |
Lưu ý
- Chỉ chính xác nếu _id là ObjectId (mặc định)
- Nếu _id tự định nghĩa (string, number), sort theo _id không đảm bảo theo thời gian
- Nên thêm trường
createdAt: new Date()khi insert để query chính xác hơn