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).
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