MongoDB query to get last inserted document?


To get last inserted document, use sort() along with limit(1).

Let us first create a collection with documents −

> 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")
}

Display all documents from a collection with the help of find() method −

> db.getLastInsertedDocument.find();

Output

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

Following is the query to get last inserted document −

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

Output

{ "_id" : ObjectId("5cefb185ef71edecf6a1f6aa"), "Name" : "Robert" }
raja
Published on 14-Jun-2019 14:19:51
Advertisements