Syntax error Identify last document from MongoDB find() result set?

Identify last document from MongoDB find() result set?



To identify the last document from MongoDB find() result set, you can use sort() in descending order. The syntax is as follows −

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

To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.identifyLastDocuementDemo.insertOne({"UserName":"Larry","UserAge":24,"UserCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a2ff4cf1f7a64fa4df57")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Chris","UserAge":21,"UserCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a3094cf1f7a64fa4df58")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"David","UserAge":25,"UserCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a3174cf1f7a64fa4df59")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Sam","UserAge":26,"UserCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a3224cf1f7a64fa4df5a")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Mike","UserAge":27,"UserCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a32e4cf1f7a64fa4df5b")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Carol","UserAge":28,"UserCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a33c4cf1f7a64fa4df5c")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c94a2ff4cf1f7a64fa4df57"),
   "UserName" : "Larry",
   "UserAge" : 24,
   "UserCountryName" : "US"
}
{
   "_id" : ObjectId("5c94a3094cf1f7a64fa4df58"),
   "UserName" : "Chris",
   "UserAge" : 21,
   "UserCountryName" : "UK"
}
{
   "_id" : ObjectId("5c94a3174cf1f7a64fa4df59"),
   "UserName" : "David",
   "UserAge" : 25,
   "UserCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c94a3224cf1f7a64fa4df5a"),
   "UserName" : "Sam",
   "UserAge" : 26,
   "UserCountryName" : "US"
}
{
   "_id" : ObjectId("5c94a32e4cf1f7a64fa4df5b"),
   "UserName" : "Mike",
   "UserAge" : 27,
   "UserCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c94a33c4cf1f7a64fa4df5c"),
   "UserName" : "Carol",
   "UserAge" : 28,
   "UserCountryName" : "UK"
}

Here is the query to identify the last document from MongoDB find() result set −

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

The following is the output −

{
   "_id" : ObjectId("5c94a33c4cf1f7a64fa4df5c"),
   "UserName" : "Carol",
   "UserAge" : 28,
   "UserCountryName" : "UK"
}
Updated on: 2019-07-30T22:30:25+05:30

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements