HOWTO · MongoDB
How to Get the Last N Records in MongoDB
This tutorial shows how to retrieve N MongoDB documents using an explicit sort order, and explains why unsorted collection order does not identify dependable recent records.
On this page
This tutorial shows how to retrieve N documents from MongoDB. Choose what “last” means first: a collection does not guarantee a default order, so a query needs an explicit sort key for dependable results. The examples below use a stock collection with item, quantity, and the automatically assigned _id field.
Get the Last N Records in MongoDB
Create a sample collection in mongosh with use get_n_records followed by db.stock.insertMany([{ item: "abc", quantity: 12 }, { item: "def", quantity: 234 }, { item: "ghi", quantity: 45 }, { item: "jkl", quantity: 345 }, { item: "mno", quantity: 243 }, { item: "pqr", quantity: 345 }, { item: "stu", quantity: 56 }, { item: "vwx", quantity: 575 }, { item: "yzz", quantity: 298 }]). MongoDB assigns each inserted document an _id; the queries can use that key to make the ordering deterministic. Replace the sample values with your own collection and chosen definition of recency.
Define What “Last” Means
“Last” can mean newest by an application timestamp, greatest by a sequence number, or the end of natural storage order. These meanings are not interchangeable. If the task is to find the newest events, sort by the timestamp field. If it is to find the largest numbered records, sort by that number. ObjectId _id values are often useful as a unique tie-breaker, but they should not replace an explicit business timestamp when that timestamp defines recency.
For deterministic results when the primary sort field can repeat, include a unique field such as _id as a secondary key. Ascending order uses 1; descending order uses -1. The sort happens before limit(N), which then returns up to N matching documents. A collection with fewer than N matches returns fewer than N.
Sort a Query and Limit the Results
For the three greatest quantities, ordered consistently when quantities tie, use db.stock.find().sort({ quantity: -1, _id: 1 }).limit(3). The expected result documents, shown without _id for readability, are [{ item: "vwx", quantity: 575 }, { item: "jkl", quantity: 345 }, { item: "pqr", quantity: 345 }]; the tied documents appear in ascending _id order. This is an expected result, not output from an executed MongoDB query. To retrieve the three smallest quantities, use db.stock.find().sort({ quantity: 1, _id: 1 }).limit(3). Its expected result is [{ item: "abc", quantity: 12 }, { item: "ghi", quantity: 45 }, { item: "stu", quantity: 56 }], also not executed database output. To ask for records most recently created according to an application timestamp, substitute that field for quantity and choose its direction; keep _id as a tie-breaker if needed.
The cursor.sort() method accepts field and direction pairs. The first query returns the largest quantity first; the second returns the smallest first. limit(3) caps either result at three documents. Sorting on a non-unique field alone can leave the relative order of tied documents unspecified, which is why adding _id makes the result order stable for a fixed data set.
Run this example:
records = [
{"item": "abc", "quantity": 12},
{"item": "def", "quantity": 234},
{"item": "ghi", "quantity": 45},
]
for record in sorted(records, key=lambda row: (row["quantity"], row["item"]))[-2:]:
print(record["item"], record["quantity"])
ghi 45
def 234
The supplied runtime ran this Python illustration and produced the output shown. It demonstrates sorting a Python list; it is not a MongoDB query, and no database execution is implied. Use the cursor.sort() examples above when querying MongoDB.
Use $natural for Natural Storage Order
Use db.stock.find().sort({ $natural: -1 }).limit(3) to request documents in reverse natural storage order, or change the value to 1 for forward natural storage order. $natural describes storage order; it does not establish a durable chronology, insertion-time guarantee, or application-defined meaning of newest. Storage order can change as data is modified or moved, so prefer an explicit field when the reader needs a dependable notion of recency.
Use Aggregation to Sort and Limit Results
The aggregation equivalent places $sort before $limit. For the three greatest quantities, use db.stock.aggregate([{ $sort: { quantity: -1, _id: 1 } }, { $limit: 3 }]). For the three smallest quantities, use db.stock.aggregate([{ $sort: { quantity: 1, _id: 1 } }, { $limit: 3 }]). To sort by a timestamp, replace quantity with that field and choose the direction that matches the task.
The $sort stage defines the ordering of the pipeline documents, and $limit keeps only the first N documents in that ordering. Including a unique tie-breaker such as _id is useful when the main field is not unique. These are MongoDB shell expressions shown inline; the packet does not include a MongoDB execution result, so no database output is asserted here.
Why skip() and count() Do Not Define the Last N Records
db.stock.find().skip(db.stock.count() - 3).limit(3) counts documents and skips an offset, but without a sort it does not identify a dependable last three. The collection has no guaranteed default order, and writes between counting and querying can also change which documents occupy an offset. The same issue applies to an unsorted find().limit(3): it returns three documents, but does not promise which three according to insertion time or business recency.
An offset can be meaningful when paired with a defined order, for example db.stock.find().sort({ quantity: 1, _id: 1 }).skip(3).limit(3) to fetch a page after the first three in that ordering. For a last-N query, sorting in the desired direction and applying limit(N) is clearer and avoids counting the full collection just to select a suffix. For large offsets, pagination by a stable key can be more efficient than repeatedly skipping earlier results.