MongoClient
MongoDB is a fast database for storing data (documents) with no complex relational logic. It can be used through direct Python method calls.
This tutorial uses a local database on a Windows computer. It uses the Community release of MongoDB. The mongo.exe and mongod.exe programs must be run first.
Here we use the MongoClient
object. We must pass a connection string to MongoClient
—this is acquired by running mongo.exe.
example_database
and example_collection
, but you can specify other names (and should).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')}
The program creates a database called example_database
. It then creates a collection in the database called example_collection
.
delete_many
with an empty dictionary argument to clear any existing data.insert_many
We pass a dictionary argument to insert_many
. Many rows (called documents) are added to the MongoDB collection.
In Python we can use a free and powerful NoSQL
database. We use MongoClient
to store documents in collections (which are inside databases).