The find()
method returns zero or more results from a MongoDB collection. With a cursor, we can iterate over these results.
We use a for
-loop to iterate all the results in a cursor. With clone()
we can copy the cursor—this way we can evaluate it twice.
To begin, we add 3 birds to a "birds" collection. We then find all birds that were spotted at a certain location (indicated by the number 10).
for
-loop.for
-loop evaluates it. With clone, we can evaluate a cloned cursor.Count
returns the number of results in a cursor. The cursor can be evaluated still.from pymongo import MongoClient client = MongoClient("mongodb://127.0.0.1:27017") db = client.animals # Reset. db.birds.delete_many({}) # Insert some birds. db.birds.insert_many([ {"name": "Sparrow", "location": 10}, {"name": "Bluebird", "location": 50}, {"name": "Robin", "location": 10}, ]) # Use find and iterate over cursor in for-loop. print("FIND") cursor = db.birds.find({"location": 10}) for doc in cursor: print(doc) # Use find and then clone the cursor. # ... This way we can evaluate it twice. print("FIND AND CLONE") cursor = db.birds.find({"location": 50}) cloned_cursor = cursor.clone() print("CURSOR 1") for doc in cursor: print(doc) print("CURSOR 2") for doc in cloned_cursor: print(doc) # Use find and then count the results. print("FIND AND COUNT") cursor = db.birds.find({"location": 10}) count_result = cursor.count() print(count_result)FIND {'name': 'Sparrow', 'location': 10, '_id': ObjectId('59f33cb325149739cc133d91')} {'name': 'Robin', 'location': 10, '_id': ObjectId('59f33cb325149739cc133d93')} FIND AND CLONE CURSOR 1 {'name': 'Bluebird', 'location': 50, '_id': ObjectId('59f33cb325149739cc133d92')} CURSOR 2 {'name': 'Bluebird', 'location': 50, '_id': ObjectId('59f33cb325149739cc133d92')} FIND AND COUNT 2
We can only evaluate a cursor once. Some methods like count()
do not evaluate the cursor—so we can still loop over its results.
For running a query twice, using clone()
is a better option than calling find()
twice. It ensures the two queries are equal.
Cursors are an important part of using MongoDB in programs. To test performance of a find()
call, we must evaluate the results in a for
-loop.