How to get element with max id in MongoDB?

MongoDBDatabaseBig Data Analytics

To get the element with a max id, you can use the find() method. To understand the above concept, let us create a collection with the document. The query is as follows −

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

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

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

The following is the output −

{
   "_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
}

Here is the query to get the element with max id −

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

The following is the output with a record with maximum id −

{
   "_id" : ObjectId("5c8bbd0880f10143d8431e20"),
   "Name" : "Robert",
   "Age" : 25
}
raja
Published on 29-Mar-2019 11:28:08
Advertisements