Home
Map
MongoDB
Cursor Examples: clone and count
This page was last reviewed on Jul 5, 2023.
Dot Net Perls
Cursor, MongoDB. The find() method returns zero or more results from a MongoDB collection. With a cursor, we can iterate over these results.
Some helpful methods. 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.
A sample program. 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).
Start We can iterate over a cursor (returned by calling the find method) in a for-loop.
Note A cursor can only be evaluated once. Using it in a for-loop evaluates it. With clone, we can evaluate a cloned cursor.
Info 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
Notes, cursor evaluation. We can only evaluate a cursor once. Some methods like count() do not evaluate the cursor—so we can still loop over its results.
Notes, clone. For running a query twice, using clone() is a better option than calling find() twice. It ensures the two queries are equal.
A summary. 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.
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 Jul 5, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.