Computer >> Máy Tính >  >> Lập trình >> MongoDB

Truy vấn MongoDB để lấy tài liệu được chèn lần cuối?

Để tải tài liệu được chèn lần cuối, hãy sử dụng sort () cùng với limit (1).

Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

> db.getLastInsertedDocument.insertOne({"Name":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefb17eef71edecf6a1f6a8")
}
> db.getLastInsertedDocument.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefb181ef71edecf6a1f6a9")
}
> db.getLastInsertedDocument.insertOne({"Name":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefb185ef71edecf6a1f6aa")
}

Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -

> db.getLastInsertedDocument.find();

Đầu ra

{ "_id" : ObjectId("5cefb17eef71edecf6a1f6a8"), "Name" : "John" }
{ "_id" : ObjectId("5cefb181ef71edecf6a1f6a9"), "Name" : "Chris" }
{ "_id" : ObjectId("5cefb185ef71edecf6a1f6aa"), "Name" : "Robert" }

Sau đây là truy vấn để lấy tài liệu được chèn lần cuối -

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

Đầu ra

{ "_id" : ObjectId("5cefb185ef71edecf6a1f6aa"), "Name" : "Robert" }