Computer >> Computer tutorials >  >> Programming >> MongoDB

MongoDB query to find last object in collection?


To find last object in collection, at first sort() to sort the values. Use limit() to get number of values i.e. if you want only the last object, then use limit(1).

Let us first create a collection with documents −

> db.demo141.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31c347fdf09dd6d08539ae")
}
> db.demo141.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31c34bfdf09dd6d08539af")
}
> db.demo141.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31c34ffdf09dd6d08539b0")
}
> db.demo141.insertOne({"Name":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31c352fdf09dd6d08539b1")
}

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

> db.demo141.find();

This will produce the following output −

{ "_id" : ObjectId("5e31c347fdf09dd6d08539ae"), "Name" : "Chris" }
{ "_id" : ObjectId("5e31c34bfdf09dd6d08539af"), "Name" : "David" }
{ "_id" : ObjectId("5e31c34ffdf09dd6d08539b0"), "Name" : "Bob" }
{ "_id" : ObjectId("5e31c352fdf09dd6d08539b1"), "Name" : "Mike" }

Following is the query to find last object in collection −

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

This will produce the following output −

{ "_id" : ObjectId("5e31c352fdf09dd6d08539b1"), "Name" : "Mike" }