So you need to get the most recent documents from your MongoDB collection?
No problem, it's an easy thing to do. And in this guide I'll show you how.
Just make sure you're in the MongoDB client and using the database that holds your collection.
Let's get started.
Start With a Sort
First up: you gotta sort.
Specifically, you'll need to sort by descending order according to when the documents were created.
Now if you're putting a timestamp on those documents, you can sort by descending order according to that timestamp.
But you won't need to do that. Instead, just sort by the ID.
Here's an example that works for the MongoDB collection that holds the pages on this website:
db.blogPosts.find({}).sort({_id:-1});
In the example above, the collection is named blogPosts. That's because it contains blog posts.
Since the collection you're working with is almost certainly named something other than blogPosts, you'll need to update that part of the text when you do the copy-and-paste thing.
The find() method lives up to its name. It's used to find documents in the database.
Those empty curly braces inside of find({}) represent an empty criteria set. In other words, that find() will return all documents in the database.
But you want only the last few. So you'll need to sort them.
You do that with a method imaginatively named sort(). But this time you're going to put some criteria inside those curly braces.
You're going to sort by the ID. That property is named _id.
But you want to sort in descending order because you want the most recent documents. That's why the -1 follows _id.
If you wanted to sort the document in ascending order (oldest documents first), just change the -1 to a 1.
Take It to the Limit
Well you're off to a good start, but as I pointed out above that find() is going to bring back every document in the collection. You probably don't want that.
Fortunately, there's a limit() method that will limit the number of documents returned. And that method doesn't even require curly braces.
Now update the search command from above to this:
db.blogPosts.find({}).sort({_id:-1}).limit(1);
Note the limit(1) on the end. That will give you the most recent document.
If you want the three (3) most recent documents, just change that .limit(1) to .limit(3).
And you can change that number to whatever you want.
Wrapping It Up
So there you go. Now you know how to get the most recent N documents from your MongoDB collection.
Try this out in your MongoDB client. Get the answers to the questions you're asking.
Have fun!
Photo by Tirachard Kumtanom from Pexels