Python MongoDB Tutorial – Using limit() with PyMongo
Last updated 5 months, 1 week ago | 400 views 75 5

When working with large datasets in MongoDB, retrieving all documents is often unnecessary and inefficient. Fortunately, MongoDB provides a simple method to limit the number of documents returned in a query.
In this tutorial, you'll learn how to use the limit()
function with PyMongo in Python to control your query results efficiently.
Table of Contents
-
What is
limit()
in MongoDB? -
Why Use
limit()
? -
Prerequisites
-
Installing PyMongo
-
Connecting to MongoDB
-
Inserting Sample Documents
-
Using
limit()
withfind()
-
Combining
limit()
withsort()
-
Full Working Example
-
Tips and Common Pitfalls
1. What is limit()
in MongoDB?
The limit()
method is used to restrict the number of documents returned by a query. For example, if you want only the first 5 records, use:
collection.find().limit(5)
❓ 2. Why Use limit()
?
-
Reduce data transfer for faster performance
-
Improve efficiency in paginated APIs
-
Useful for previewing data
-
Ideal in testing or sampling records
⚙️ 3. Prerequisites
-
Python 3.x installed
-
MongoDB running locally or on MongoDB Atlas
-
Basic knowledge of MongoDB and Python
4. Installing PyMongo
Install the PyMongo package using pip:
pip install pymongo
5. Connecting to MongoDB
Connect to a local MongoDB database:
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["students"]
6. Inserting Sample Documents
Insert multiple records into the students
collection:
collection.insert_many([
{"name": "Alice", "score": 87},
{"name": "Bob", "score": 91},
{"name": "Charlie", "score": 78},
{"name": "David", "score": 85},
{"name": "Eve", "score": 92},
{"name": "Frank", "score": 74}
])
7. Using limit()
with find()
Retrieve only the first 3 documents:
results = collection.find().limit(3)
for student in results:
print(student)
Output will show only three student documents.
8. Combining limit()
with sort()
You can combine limit()
with sort()
to get top or bottom records:
# Top 2 scorers
results = collection.find().sort("score", -1).limit(2)
for student in results:
print(student)
This sorts by score
in descending order and returns the top 2 scorers.
9. Full Working Example
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["students"]
# Insert sample data
collection.insert_many([
{"name": "Alice", "score": 87},
{"name": "Bob", "score": 91},
{"name": "Charlie", "score": 78},
{"name": "David", "score": 85},
{"name": "Eve", "score": 92},
{"name": "Frank", "score": 74}
])
# Limit results to 3
print("Limit to 3 students:")
for student in collection.find().limit(3):
print(student)
# Top 2 scorers
print("\nTop 2 scorers:")
for student in collection.find().sort("score", -1).limit(2):
print(student)
10. Tips and Common Pitfalls
Tip / Pitfall | Description |
---|---|
✅ Always use limit() in UI views |
Avoid over-fetching records |
❌ limit() doesn’t guarantee order |
Use sort() with limit() |
✅ Use in pagination logic | Combine with skip() for pagination |
Avoid hardcoded limits in logic | Make limits configurable |
✅ Use count_documents() to check totals |
Useful for paginated API responses |
✅ Conclusion
The limit()
method in PyMongo is a simple yet powerful way to control data output from MongoDB queries. Whether you're building paginated results, analyzing top records, or just testing your collections, limit()
helps you avoid unnecessary load and keep your application efficient.
Keep it fast. Keep it clean. Use limit()
.