Of course! Finding the "k" most recent documents in mongosh is a very common task. The key is to combine the sort() and limit() methods.
The best method depends on how you are tracking time in your documents.
Method 1: Sorting by _id (Most Common)
If you are using MongoDB's default ObjectId for your _id field, you're in luck. The first 4 bytes of an ObjectId represent a timestamp, so you can sort by _id to get a chronological order. This is the simplest and often most efficient way.
The Command
To find the 5 most recent documents in a collection named logs:
javascript
// Replace `logs` with your collection name and `5` with your desired number (k)
db.logs.find().sort({ _id: -1 }).limit(5)
Breakdown
db.logs.find(): Selects all documents in the logs collection.
.sort({ _id: -1 }): This is the crucial part.
sort() orders the results.
{ _id: -1 } tells MongoDB to sort by the _id field in descending order (-1). Descending order means the newest/largest values come first.
.limit(5): Restricts the output to the first 5 documents after the sort has been applied.
Method 2: Sorting by a Dedicated Timestamp Field
It is a very good practice to have an explicit timestamp field, often named createdAt or timestamp. This makes your queries more readable and intention-clear.
To find the 10 most recent documents based on the createdAt field:
javascript
// Replace `mycollection` with your collection name and `10` with your desired number (k)
db.mycollection.find().sort({ createdAt: -1 }).limit(10)
This works exactly like the first method, but it sorts on your custom createdAt field instead of the _id.
Full Example in mongosh
Let's walk through a complete example.
1. Insert some sample data into a posts collection:
javascript
db.posts.insertMany([
{ title: "My First Post", content: "...", createdAt: new Date("2023-01-15T12:00:00Z") },
{ title: "A Later Post", content: "...", createdAt: new Date("2023-05-20T14:00:00Z") },
{ title: "The Most Recent Post", content: "...", createdAt: new Date("2023-10-27T09:00:00Z") },
{ title: "A Post from Yesterday", content: "...", createdAt: new Date("2023-10-26T18:00:00Z") },
{ title: "An Old Post", content: "...", createdAt: new Date("2022-12-01T10:00:00Z") }
])
2. Run the query to get the 3 most recent posts:
javascript
db.posts.find().sort({ createdAt: -1 }).limit(3)
3. Expected Output:
The command will return the three documents with the most recent createdAt dates, in order from newest to oldest.
json
[
{
"_id": ObjectId("..."),
"title": "The Most Recent Post",
"content": "...",
"createdAt": ISODate("2023-10-27T09:00:00.000Z")
},
{
"_id": ObjectId("..."),
"title": "A Post from Yesterday",
"content": "...",
"createdAt": ISODate("2023-10-26T18:00:00.000Z")
},
{
"_id": ObjectId("..."),
"title": "A Later Post",
"content": "...",
"createdAt": ISODate("2023-05-20T14:00:00.000Z")
}
]
⭐ Performance Best Practice: Create an Index
For this query to be fast on a large collection, you must have an index on the field you are sorting by. Without an index, MongoDB has to load all documents into memory to sort them, which is very slow and inefficient.
To create an index on the createdAt field, run this command:
javascript
db.mycollection.createIndex({ createdAt: -1 })
Creating the index with the same sort order (-1 for descending) as your query allows MongoDB to read the documents in the correct order directly from the index, which is extremely fast.
The _id field is automatically indexed by default, so you don't need to do anything for Method 1.