Python MongoDB - Limit Query
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.
Syntax
collection.find().limit(n)
Parameter: n (int) is the maximum number of documents to return.
Here is our sample data.
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
Data inserted.


Explanation:
- MongoClient() connects to the MongoDB server running on localhost at the default port 27017.
- delete_many({}) clears any existing documents from the collection to prevent duplicate entries.
- insert_many(data) inserts the list of sample documents into the collection.
Examples
Example 1: Limit to first 3 documents
#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

Explanation: find().limit(3) returns only the first 3 documents from the collection.
Example 2: Combine with sort
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

Explanation: Sorts the documents by amount in descending order and limits the output to the top 2.
Example 3: Limit results based on a filter
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

Explanation: Filters documents where user is "Cody" and limits the result to just 1 document (the first match based on insertion order).
Related Articles