MongoDB Limit
Learn how to use PyMongo's limit() method to cap query results, combine it with skip() for pagination, and chain it with sort() for ordered output.
The limit() method in PyMongo lets you cap the number of documents returned by a query. This page explains what limit() does, when to use it, how to combine it with skip() for pagination, and how to chain it with sort() for ordered, bounded result sets.
Prerequisites
You need PyMongo installed and a running MongoDB instance. Install the driver with:
pip install pymongoThen connect to your database:
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
col = db["customers"]If you are new to connecting and inserting documents, see the MongoDB Get Started and MongoDB Insert chapters first.
What limit() Does
Calling .limit(n) on a cursor tells MongoDB to return at most n documents. Without it, find() returns every matching document — which can be expensive on large collections.
# Returns ALL documents — can be slow on large collections
all_docs = col.find()
# Returns at most 5 documents
five_docs = col.find().limit(5)Passing 0 to limit() is treated the same as not calling it at all: MongoDB returns all matching documents.
# These two are equivalent — both return all documents
col.find().limit(0)
col.find()Basic Example
The following script inserts ten sample customer documents and then retrieves only the first three:
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
col = db["customers"]
# Insert sample data (skip if your collection already has data)
col.drop()
names = ["Alice", "Bob", "Charlie", "Diana", "Eve",
"Frank", "Grace", "Hank", "Iris", "Jack"]
col.insert_many([{"name": n, "rank": i + 1} for i, n in enumerate(names)])
# Retrieve only the first 3 documents
results = col.find({}, {"_id": 0}).limit(3)
for doc in results:
print(doc)Expected output:
{'name': 'Alice', 'rank': 1}
{'name': 'Bob', 'rank': 2}
{'name': 'Charlie', 'rank': 3}The second argument to find() is a projection — {"_id": 0} suppresses the _id field so the output is easier to read.
Combining limit() with sort()
limit() is most useful when paired with sort(). Without sorting, MongoDB returns documents in natural order (insertion order on a fresh collection, but not guaranteed after updates or deletes). Sorting first ensures that the "top N" results are meaningful.
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
col = client["mydatabase"]["customers"]
# Top 3 customers by rank (ascending)
top3 = col.find({}, {"_id": 0}).sort("rank", pymongo.ASCENDING).limit(3)
print("Top 3 by rank:")
for doc in top3:
print(doc)
# Bottom 3 customers by rank (descending = highest rank number first)
bottom3 = col.find({}, {"_id": 0}).sort("rank", pymongo.DESCENDING).limit(3)
print("\nBottom 3 by rank:")
for doc in bottom3:
print(doc)Expected output:
Top 3 by rank:
{'name': 'Alice', 'rank': 1}
{'name': 'Bob', 'rank': 2}
{'name': 'Charlie', 'rank': 3}
Bottom 3 by rank:
{'name': 'Jack', 'rank': 10}
{'name': 'Iris', 'rank': 9}
{'name': 'Hank', 'rank': 8}See the MongoDB Sort chapter for a full guide to sorting options.
Pagination with skip() and limit()
skip(n) tells MongoDB to discard the first n documents before applying limit(). Together they implement page-based pagination:
page_1 = skip(0).limit(page_size)
page_2 = skip(page_size).limit(page_size)
page_N = skip((N-1) * page_size).limit(page_size)Here is a reusable helper that fetches one page at a time:
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
col = client["mydatabase"]["customers"]
def get_page(collection, page_number, page_size, sort_field="rank"):
"""Return one page of documents (1-indexed page numbers)."""
offset = (page_number - 1) * page_size
cursor = (
collection.find({}, {"_id": 0})
.sort(sort_field, pymongo.ASCENDING)
.skip(offset)
.limit(page_size)
)
return list(cursor)
# Fetch pages of 3 documents each
page1 = get_page(col, page_number=1, page_size=3)
page2 = get_page(col, page_number=2, page_size=3)
page3 = get_page(col, page_number=3, page_size=3)
print("Page 1:", page1)
print("Page 2:", page2)
print("Page 3:", page3)Expected output:
Page 1: [{'name': 'Alice', 'rank': 1}, {'name': 'Bob', 'rank': 2}, {'name': 'Charlie', 'rank': 3}]
Page 2: [{'name': 'Diana', 'rank': 4}, {'name': 'Eve', 'rank': 5}, {'name': 'Frank', 'rank': 6}]
Page 3: [{'name': 'Grace', 'rank': 7}, {'name': 'Hank', 'rank': 8}, {'name': 'Iris', 'rank': 9}]skip() performance caveat
skip() works by scanning and discarding the first n documents before returning results. On very large collections (millions of documents), a large skip() value is slow because MongoDB must still read all the skipped documents. For high-traffic pagination over big data sets, use a range query on an indexed field instead:
# Instead of skip(1000).limit(10), remember the last _id from the previous page
# and filter: {"_id": {"$gt": last_seen_id}}
# This is O(log n) with an index rather than O(n)Combining limit() with a Filter Query
limit() works with any find() query, not just bare find({}):
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
col = client["mydatabase"]["customers"]
# Find customers with rank greater than 5, return only the first 3
query = {"rank": {"$gt": 5}}
results = col.find(query, {"_id": 0}).sort("rank", pymongo.ASCENDING).limit(3)
for doc in results:
print(doc)Expected output:
{'name': 'Frank', 'rank': 6}
{'name': 'Grace', 'rank': 7}
{'name': 'Hank', 'rank': 8}For more on filter operators ($gt, $lt, $in, etc.), see the MongoDB Query chapter.
Method Chaining Order
PyMongo builds the query on the server side, so the order in which you chain sort(), skip(), and limit() in Python does not change the result — MongoDB always applies them in the sequence: filter → sort → skip → limit. The following two statements are equivalent:
col.find().sort("rank", 1).skip(2).limit(3)
col.find().limit(3).skip(2).sort("rank", 1) # same resultWriting them in the logical order (sort → skip → limit) is a convention that makes code easier to read.
Quick Reference
| Method | Purpose | Example |
|---|---|---|
.limit(n) | Return at most n documents | .find().limit(10) |
.skip(n) | Skip the first n documents | .find().skip(20) |
.sort(field, dir) | Order before limiting | .find().sort("rank", 1).limit(5) |
.limit(0) | No limit (returns all) | .find().limit(0) |
Related Chapters
- MongoDB Find — querying documents with
find()andfind_one() - MongoDB Query — filtering with comparison and logical operators
- MongoDB Sort — ordering results with
sort() - MongoDB Insert — adding documents to a collection
- MongoDB Update — modifying existing documents