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

To publish the latest N records with sorting in MongoDB, use the sort() method combined with limit(). The sort() method orders documents, while limit() restricts the number of returned records.

Syntax

db.collection.find().sort({field: -1}).limit(N);

Where -1 sorts in descending order, 1 for ascending order, and N is the number of records to return.

Create Sample Data

db.demo454.insertMany([
    {"ClientName": "Chris"},
    {"ClientName": "John"},
    {"ClientName": "Bob"},
    {"ClientName": "David"},
    {"ClientName": "Mike"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e7cce8cdbcb9adb296c95c0"),
        ObjectId("5e7cce95dbcb9adb296c95c1"),
        ObjectId("5e7cce9fdbcb9adb296c95c2"),
        ObjectId("5e7ccea6dbcb9adb296c95c3"),
        ObjectId("5e7cceafdbcb9adb296c95c4")
    ]
}

View All Documents

db.demo454.find();
{ "_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" }

Example: Get Latest 3 Records by Name (Descending)

To get the top 3 clients sorted by name in descending order ?

db.demo454.find().sort({ClientName: -1}).limit(3);
{ "_id": ObjectId("5e7cceafdbcb9adb296c95c4"), "ClientName": "Mike" }
{ "_id": ObjectId("5e7cce95dbcb9adb296c95c1"), "ClientName": "John" }
{ "_id": ObjectId("5e7ccea6dbcb9adb296c95c3"), "ClientName": "David" }

Key Points

  • Use sort({field: -1}) for descending order, sort({field: 1}) for ascending
  • limit(N) restricts results to the first N documents after sorting
  • For truly "latest" records by insertion time, sort by _id instead of custom fields

Conclusion

Combine sort() and limit() to efficiently retrieve the top N records. The sort order determines which records are considered "latest" ? use descending sort for newest-first results.

Updated on: 2026-03-15T03:02:05+05:30

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements