How to continuously publish the latest N records with sorting using MongoDB?


To publish the latest N records with sorting, use sort() along with limit(). Here, set the number of records you want to show with limit(). Let us create a collection with documents −

> db.demo454.insertOne({"ClientName":"Chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7cce8cdbcb9adb296c95c0")
}
> db.demo454.insertOne({"ClientName":"John"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7cce95dbcb9adb296c95c1")
}
> db.demo454.insertOne({"ClientName":"Bob"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7cce9fdbcb9adb296c95c2")
}
> db.demo454.insertOne({"ClientName":"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7ccea6dbcb9adb296c95c3")
}
> db.demo454.insertOne({"ClientName":"Mike"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7cceafdbcb9adb296c95c4")
}

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

> db.demo454.find();

This will produce the following output −

{ "_id" : ObjectId("5e7cce8cdbcb9adb296c95c0"), "ClientName" : "Chris" }
{ "_id" : ObjectId("5e7cce95dbcb9adb296c95c1"), "ClientName" : "John" }
{ "_id" : ObjectId("5e7cce9fdbcb9adb296c95c2"), "ClientName" : "Bob" }
{ "_id" : ObjectId("5e7ccea6dbcb9adb296c95c3"), "ClientName" : "David" }
{ "_id" : ObjectId("5e7cceafdbcb9adb296c95c4"), "ClientName" : "Mike" }

Following is the query to publish the latest N records using SORT() and LIMIT() in MongoDB −

> db.demo454.find().sort({ClientName:-1}).limit(3);

This will produce the following output −

{ "_id" : ObjectId("5e7cceafdbcb9adb296c95c4"), "ClientName" : "Mike" }
{ "_id" : ObjectId("5e7cce95dbcb9adb296c95c1"), "ClientName" : "John" }
{ "_id" : ObjectId("5e7ccea6dbcb9adb296c95c3"), "ClientName" : "David" }

Updated on: 11-May-2020

53 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements