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