from pymongo import MongoClient
# Run mongod.exe before running this program.
# Run mongo.exe to get the database connection string.
client = MongoClient(
"mongodb://127.0.0.1:27017")
# Specify the database name after the client object.
db = client.example_database
# Ensure everything is deleted from example collection.
# ... The name can anything to specify a collection.
db.example_collection.
delete_many({})
db.example_collection.
insert_many([
{"type": "cat", "weight": 25, "color": "orange"},
{"type": "dog", "weight": 35, "color": "black"},
{"type": "cat", "weight": 10, "color": "black"}
])
# Find all things.
cursor = db.example_collection.
find({})
print(
"FIND ALL")
for c in cursor:
print(c)
# Find all animals that are black.
cursor = db.example_collection.
find({"color": "black"})
print(
"FIND COLOR BLACK")
for c in cursor:
print(c)
# Find all dogs.
cursor = db.example_collection.
find({"type": "dog"})
print(
"FIND DOG")
for c in cursor:
print(c)
FIND ALL
{'type': 'cat', 'weight': 25, 'color': 'orange',
'_id': ObjectId('59ee4d922514973b084100a7')}
{'type': 'dog', 'weight': 35, 'color': 'black',
'_id': ObjectId('59ee4d922514973b084100a8')}
{'type': 'cat', 'weight': 10, 'color': 'black',
'_id': ObjectId('59ee4d922514973b084100a9')}
FIND COLOR BLACK
{'type': 'dog', 'weight': 35, 'color': 'black',
'_id': ObjectId('59ee4d922514973b084100a8')}
{'type': 'cat', 'weight': 10, 'color': 'black',
'_id': ObjectId('59ee4d922514973b084100a9')}
FIND DOG
{'type': 'dog', 'weight': 35, 'color': 'black',
'_id': ObjectId('59ee4d922514973b084100a8')}