Python Tutorial
Python MongoDB - Limit
Cap how many documents a query returns, and page through results.
limit()
Chain .limit(n) onto a cursor to return at most n documents — ideal for previews and top-N lists.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
customers = client["mydatabase"]["customers"]
for doc in customers.find().limit(5):
print(doc) # at most 5 documentsCombine With a Filter and Sort
limit chains with find filters and sort. MongoDB applies the sort first, then the limit.
products = client["shop"]["products"]
top3 = products.find({"in_stock": True}).sort("price", -1).limit(3)
for p in top3:
print(p["name"], p["price"]) # three most expensive in-stock itemsPagination With skip and limit
Skip past earlier pages, then limit to one page's worth. Always sort so pages are stable.
def get_page(collection, page, per_page=10):
return list(
collection.find()
.sort("_id")
.skip((page - 1) * per_page)
.limit(per_page))
print(get_page(customers, page=2, per_page=10)) # documents 11-20Large skip values are slow because MongoDB walks and discards the skipped documents. For deep pages, use keyset pagination instead.
Keyset (Range) Pagination
Remember the last _id from the previous page and filter for greater ids — this jumps straight to the next batch without scanning.
from bson import ObjectId
last_id = ObjectId("652f000000000000000000aa") # last _id of previous page
next_page = (customers.find({"_id": {"$gt": last_id}})
.sort("_id")
.limit(10))Counting Without Fetching
limit does not tell you the total. Use count_documents for the full count to build page numbers.
total = customers.count_documents({})
pages = (total + 9) // 10 # ceil division for per_page = 10
print("Total pages:", pages)Best Practices
- Pair
limitwithsortfor consistent, repeatable pages. - Prefer keyset pagination over large
skipoffsets. - Index sort fields so limited queries stay fast.
- Use
limitin development to avoid pulling entire large collections.
Try It Yourself
Exercise 1: Return the first 5 documents sorted by name.
Show solution
coll.find().sort("name").limit(5)Exercise 2: Why prefer keyset pagination over a large skip?
Show solution
A large skip still walks and discards every skipped document; filtering by the last seen id jumps straight to the next batch.
📘 Real-World Deep Dive
Knowing <strong>MongoDB Limit (MongoDB)</strong> well is what turns MongoDB from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of MongoDB Limit that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
from pymongo import MongoClient
db = MongoClient().shop
print(list(db.orders.find().limit(2)))Expected Output
(see source)Common mistakes
- Inserting a
dictwith embeddeddatetimeworks, but naivedatetime(without UTC) leads to subtle comparison bugs. - Queries with type-mismatched values silently return no results — cast at the boundary or use
bsoncodecs. find()returns a cursor — calllist(cursor)only once you intend to materialise results.- Treating MongoDB Limit as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Project only the fields you need:
collection.find({}, {"name": 1}). - Use
bulk_writeinstead of looping over single inserts / updates — order-of-magnitude faster. - Create indexes:
collection.create_index([("field", pymongo.ASCENDING)]). - When working with MongoDB, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.