0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Find Last N Documents Easily

Use db.collection.find().sort({_id: -1}).limit(n) to get the last n documents based on insertion order in MongoDB.
📋

Examples

InputFind last 2 documents from collection with _id 1,2,3,4
Output[{_id:4, ...}, {_id:3, ...}]
InputFind last 3 documents from collection with timestamps
Output[{_id:5, ...}, {_id:4, ...}, {_id:3, ...}]
InputFind last 5 documents from empty collection
Output[]
🧠

How to Think About It

To find the last n documents, think of sorting the documents in reverse order by their unique identifier or timestamp, then picking the first n from that sorted list. This way, you get the most recent entries first.
📐

Algorithm

1
Access the collection you want to query.
2
Sort the documents by the _id field in descending order to get newest first.
3
Limit the result to n documents to get only the last n entries.
4
Return the resulting documents.
💻

Code

mongodb
const n = 3;
const lastDocuments = db.collection.find().sort({_id: -1}).limit(n).toArray();
printjson(lastDocuments);
Output
[ {"_id": 5, "name": "Eve"}, {"_id": 4, "name": "Dave"}, {"_id": 3, "name": "Carol"} ]
🔍

Dry Run

Let's trace finding last 3 documents from a collection with _id 1 to 5.

1

Sort documents by _id descending

Documents order after sort: 5, 4, 3, 2, 1

2

Limit to 3 documents

Selected documents: 5, 4, 3

StepDocuments
After sort[5, 4, 3, 2, 1]
After limit[5, 4, 3]
💡

Why This Works

Step 1: Sorting by _id descending

Using sort({_id: -1}) orders documents from newest to oldest because MongoDB ObjectIds increase over time.

Step 2: Limiting results

Applying limit(n) restricts the output to only the last n documents after sorting.

🔄

Alternative Approaches

Sort by timestamp field
mongodb
const n = 3;
const lastDocs = db.collection.find().sort({createdAt: -1}).limit(n).toArray();
printjson(lastDocs);
Use this if documents have a timestamp field instead of relying on _id.
Use aggregation pipeline
mongodb
const n = 3;
const lastDocs = db.collection.aggregate([
  { $sort: { _id: -1 } },
  { $limit: n }
]).toArray();
printjson(lastDocs);
Aggregation can be more flexible for complex queries but is slightly more verbose.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting the documents takes O(n log n) time where n is the number of documents in the collection.

Space Complexity

The query uses O(n) space to hold documents during sorting and limiting.

Which Approach is Fastest?

Sorting by indexed fields like _id is fastest; aggregation adds overhead but offers flexibility.

ApproachTimeSpaceBest For
Find + sort + limitO(n log n)O(n)Simple last n documents retrieval
Sort by timestamp fieldO(n log n)O(n)When timestamp is available and reliable
Aggregation pipelineO(n log n)O(n)Complex queries needing more stages
💡
Always sort by a field that reflects insertion order, like _id or a timestamp, before limiting results.
⚠️
Not sorting before limiting, which returns arbitrary documents instead of the last n.