Saturday, 28 November 2020

How to fetch last 'n' records from a collection in MongoDB? | MongoDB Tutorial for Beginners

🚀 Master MongoDB Data Retrieval with Ram N Java!

Want to query your data like a professional? Subscribe now for high-quality, beginner-friendly tech tutorials that make complex database operations simple and easy to master!

🔔 SUBSCRIBE FOR FREE NOW

How to Fetch the Last 'n' Records in MongoDB

Retrieving the most recent entries in a database is a frequent requirement, whether you're building a "recent activity" feed or checking the latest logs. In MongoDB, there isn't a single "last" command, but by combining three powerful methods—sort(), limit(), and reverse()—you can fetch exactly what you need.

The Three-Step Strategy

To get the latest 'n' records, you follow a simple logical flow: sort the data in descending order, take the top 'n' results, and then (optionally) flip them back to chronological order.

1. Sort by ID or Timestamp

The _id field in MongoDB contains a timestamp. Sorting by _id: -1 puts the newest documents at the top of the list.

2. Apply a Limit

Use the limit(n) method to tell MongoDB exactly how many of those newest documents you want to retrieve.

// Fetch the last 5 records added to the users collection db.users.find().sort({ "_id": -1 }).limit(5)

💡 Quick Beginner Tip

Remember that sorting in descending order (-1) effectively moves the end of the collection to the beginning for the purpose of your query. This is the most efficient way to access "recent" data without scanning the entire collection!

Level Up Your MongoDB Skills:

No comments:

Post a Comment

Tutorials