Home
Map
Limit ExampleUse the MongoDB find method with a limit on the cursor to get a certain number of results.
MongoDB
This page was last reviewed on Oct 11, 2023.
Limit, MongoDB. A MongoDB query may return many results—more than we need. With a limit() call on the cursor returned by find() we can reduce the number of results.
Often in programs we want to display just 10 or 20 results. A limit is ideal for restricting the number of returns for a screen of information.
Example program. This program uses some MongoClient code to set up an "animals" collection in a "veterinarian" database. Everyone loves animals (although not cleaning up after them).
Here We invoke the find() method to find dogs in our tiny example collection. There are 3 dogs present.
Tip We use a limit() call on our cursor to restrict the number of results to 2. Usually a limit will be higher than 2.
from pymongo import MongoClient client = MongoClient("mongodb://127.0.0.1:27017") db = client.veterinarian # Clear our collection. db.animals.delete_many({}) # Insert some animals into a collection. db.animals.insert_many([ {"type": "cat", "weight": 15, "color": "orange"}, {"type": "dog", "weight": 10, "color": "black"}, {"type": "dog", "weight": 35, "color": "black"}, {"type": "dog", "weight": 20, "color": "white"} ]) # Find all dogs with limit of 2 results. cursor = db.animals.find({"type": "dog"}).limit(2) print("FIND DOG LIMIT 2") for c in cursor: print(c)
FIND DOG LIMIT 2 {'type': 'dog', '_id': ObjectId('59ef473525149701747bc4c0'), 'color': 'black', 'weight': 10} {'type': 'dog', '_id': ObjectId('59ef473525149701747bc4c1'), 'color': 'black', 'weight': 35}
Notes, limit. In SQL we combine a "LIMIT" into the query language. But in MongoDB we use direct Python method calls. We use "limit" after the find call.
A review. To create more complex queries in MongoDB we chain method calls after find(). Not just limit() can be used—other methods like sort and skip are available.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 11, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.