Last Updated : 15 Jul, 2025
In PyMongo, the limit() method is used to restrict the number of documents returned by a query. It’s especially useful when you want to preview only a few records from a large dataset.
Syntaxcollection.find().limit(n)
Parameter: n (int) is the maximum number of documents to return.
Here is our sample data. Python
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c['grpDB']
col = db['sales']
data = [
{"_id": 1, "user": "Amit", "product": "Pen", "amount": 5},
{"_id": 2, "user": "Drew", "product": "Pencil", "amount": 3},
{"_id": 3, "user": "Amit", "product": "Notebook", "amount": 15},
{"_id": 4, "user": "Cody", "product": "Pen", "amount": 7},
{"_id": 5, "user": "Drew", "product": "Notebook", "amount": 12},
{"_id": 6, "user": "Cody", "product": "Eraser", "amount": 2},
{"_id": 7, "user": "Amit", "product": "Pen", "amount": 10}
]
col.delete_many({})
col.insert_many(data)
print("Data inserted.")
Output
Sample dataData inserted.
Explanation:
#Driver Code Starts
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c['grpDB']
col = db['sales']
#Driver Code Ends
res = col.find().limit(3)
for doc in res:
#Driver Code Starts
print(doc)
#Driver Code Ends
Output
First 3 docsExplanation: find().limit(3) returns only the first 3 documents from the collection.
Example 2: Combine with sort Python
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c['grpDB']
col = db['sales']
res = col.find().sort("amount", -1).limit(2)
for doc in res:
print(doc)
Output
Top 2 by amountExplanation: Sorts the documents by amount in descending order and limits the output to the top 2.
Example 3: Limit results based on a filter Python
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c['grpDB']
col = db['sales']
res = col.find({"user": "Cody"}).limit(1)
for doc in res:
print(doc)
Output
First Cody recordExplanation: Filters documents where user is "Cody" and limits the result to just 1 document (the first match based on insertion order).
Related Articles
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4