Use MongoDB Aggregate and select only top record (descending)


For descending order, use -1, which specifies sorting order for sort(), Let us create a collection with documents −

> db.demo267.insertOne({id:100,"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4811951627c0c63e7dbaab")
}
> db.demo267.insertOne({id:100,"Name":"Adam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48119e1627c0c63e7dbaac")
}
> db.demo267.insertOne({id:100,"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4811a51627c0c63e7dbaad")
}
> db.demo267.insertOne({id:100,"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4811ab1627c0c63e7dbaae")
}

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

> db.demo267.find().pretty();
{
   "_id" : ObjectId("5e4811951627c0c63e7dbaab"),
   "id" : 100,
   "Name" : "Chris"
}
{
   "_id" : ObjectId("5e48119e1627c0c63e7dbaac"),
   "id" : 100,
   "Name" : "Adam"
}
{
   "_id" : ObjectId("5e4811a51627c0c63e7dbaad"),
   "id" : 100,
   "Name" : "David"
}
{ "_id" : ObjectId("5e4811ab1627c0c63e7dbaae"), "id" : 100, "Name" : "Bob" }

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

> db.demo267.find().sort({Name:-1}).limit(1);

This will produce the following output −

{ "_id" : ObjectId("5e4811a51627c0c63e7dbaad"), "id" : 100, "Name" : "David" }

Updated on: 31-Mar-2020

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements