w3resource

How to Retrieve the Last N Records in MongoDB?

Retrieve last N Records in MongoDB with sorting and limit

To retrieve the last N records in MongoDB, you typically need to sort the documents in reverse order (descending) by a timestamp or another field that indicates the order, and then limit the result to N documents. MongoDB does not directly support retrieving the last records, so sorting and limiting is the approach to use. Here’s a detailed explanation, syntax, example code, and how this query works.

Description:

In MongoDB, retrieving the last N records is commonly done by sorting the documents in descending order based on a specific field, such as a timestamp or an auto-incremented field. By doing this, you can use the limit function to fetch the latest N records in the sorted order. This approach is effective for retrieving recent entries in time-based data.

Syntax:

The syntax for getting the last N records is:

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

Explanation:

  • <collection>: The name of the collection to query.
  • <field>: The field to sort by, typically a date or timestamp.
  • -1: Specifies descending order, so the latest records appear first.
  • N: The number of documents you want to retrieve.

Example Code:

Here's an example that queries a posts collection to get the last 5 records based on a createdAt field (a timestamp indicating when each post was created).

Code:

// Query the 'posts' collection
db.posts.find()
  // Sort the documents by 'createdAt' in descending order
  .sort({ createdAt: -1 })
  // Limit the result to the last 5 records
  .limit(5)

Explanation:

  • db.posts.find()
    This starts the query in the posts collection.
  • .sort({ createdAt: -1 })
    This sorts the documents by the createdAt field in descending order, so the most recent records are listed first.
  • .limit(5)
    Limits the result set to 5 documents, effectively retrieving the last 5 records based on the specified sorting.

By combining .sort() and .limit(), MongoDB will return the last 5 records based on the createdAt timestamp in descending order. This method is commonly used when you need the latest entries in time-series data.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/snippets/retrieve-last-n-records-in-mongodb-with-sorting-and-limit.php