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.
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).
find()
method to find dogs in our tiny example collection. There are 3 dogs present.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}
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.
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.