Home
MongoDB
Limit Example
Updated Oct 11, 2023
Dot Net Perls
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 11, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen