How to use MongoDB with Python and PyMongo

If you want to use MongoDB with Python, then PyMongo is your best option. The standard driver library is very user friendly and clear to use. Creating and changing your own databases and collections can be done in just a few steps.

What’s behind PyMongo?

The No-SQL database management system MongoDB has developed into a reliable alternative to MySQL in the last few years. What’s more is that with the right drivers, you can use your programing language of choice to create objects. PyMongo is the official driver package you will need to control MongoDB with Python.

Note

MongoDB saves data as JSON documents which can be collated and indexed for better classification within Collections. You can use MongoDB commands to open data, sort, change, collate or remove them.

How to install PyMongo

If you want to employ the driver library to use MongoDB with Python, then we would recommend the PIP Python package manager. You can use it to install PyMongo at any time on the device or server you want to use MongoDB from. You can do this by using the following command:

python -m pip install pymongo

How to create databases in MongoDB with Python

After installing PyMongo, you can connect to MongoDB, using MongoClient to do this. You can do this with the following command (replace the placeholder “<<MongoDB URL>>” with the relevant connection string):

from pymongo import MongoClient
database = MongoClient ('<<MongoDB URL>>')

There are three standard databases in MongoDB: local, admin and config. However, if you want to use MongoDB effectively with Python when you will need additional databases. You can easily create them using the abbreviation “db”. If the named database already exists, it will be opened. If there is no database with the corresponding name, MongoDB will create it for you. The command for a new database called “client list” will look like this:

db = client.clientlist

If you want to further secure your data, you can also set up an authentication process at this point. The corresponding data are then stored in the “admin” database as standard. You can set up authentication as follows:

connection = MongoClient ("localhost",
username = "user",
password = "password",
authSource = "admin",
authMechanism = "SCRAM-SHA-256")

Add Collections with PyMongo

As soon as you have created a database, you can easily add Collections. However, these will only actually be taken into consideration by the system when they contain documents. To create a new Collection in MongoDB with Python, you can use the following entry:

collection = database ["clients_unitedstates"]

Add MongoDB database entries with Python

You can now fill these new Collections with content. New documents will be added to them and can be opened, combined or otherwise managed as needed. An example of a document would look as follows:

clientInfo = {
"name" : "Smith",
"address" : "10 Main Street",
"ZIP" : "20097",
"city" : "Boston"
}
collection.insert_one(clientInfo)

You can add multiple entries at the same time by using “insert_many”. Each one of these entries will be automatically assigned a unique “_id” field allowing it to be selected and used individually later. You can use “insert many” as follows:

clientInfo =[
{
"name" : "Smith",
"address" : "10 Main Street",
"ZIP" : "20097",
"city" : "Boston"
}
{
"name" : "Jones",
"address" : "1 Maple Street",
"ZIP" : "10315",
"city" : "Baltimore"
}
{
"name" : "Nguyen",
"address" : "42 Elm Street",
"ZIP" : "44866",
"city" : "Birmingham"
}
]
collection.insert_many(clientInfo)

Opening MongoDB data with Python

Being able to open data later without problems is as important as being able to save data in the first place. You have various options to do this, and the most practical one is to use MongoDB find. Here’s how to do open one of the examples above:

data = collection.find ( { "city" : "Boston" } )
print (data
# {
"_id" : ObjectID ("7fe4a462991acf79e22c" ),
"name" : "Smith", "address" : "10 Main Street",
"ZIP" : "20097",
"city" : "Boston"
}

Change MongoDB entries with Python

Data can change over time. This means it might be necessary to change MongoDB entries. The combination of MongoDB and Python gives you several options to amend your entries. Alongside changes to a single document, you can also make amendments to more or all entries in a database or a particular Collection. Some suitable methods include, among others, “update_one” and “update_many”.

“Update_one” example

To give you an illustration of “update_one”, let’s look at a simple address change. Let’s pretend that our client “Smith” has moved to the same city. Instead of deleting their entry completely and entering it again, you can amend it simply as follows:

import pymongo
myclient = pymongo.MongoClient ("<mongodb url="">")</mongodb>
mydb = myclient ["clientlist"]
mycol = mydb [ "clients_unitedstates" ]
myquery = { "address" : "10 Main Street” }
newvalues = { "$set" : {"address" : "82 Main Street" } }
mycol.update_one (myquery, newvalues)
#print "customer" after the update:
for x in mycol.find ():
print (x)

“update_many”

If you would like to change all documents which meet certain criteria, you can do this using the “update_many” command. In the following example all clients whose names being with “M” have moved to a new city:

import pymongo
myclient = pymongo.MongoClient ("<mongodb url="">")</mongodb>
mydb = myclient ["clientlist"]
mycol = mydb [ "clients_unitedstates" ]
myquery = { "name" : "$regex" : "^M" }
newvalues = { "$set" : { "city" : "Portland" } }
x = mycol.update_many (myquery, newvalues)
print (x.modified_count, "documents updated.")

Delete MongoDB documents with Python

You also have the option to delete documents. This works similarly to changing entries or multiple documents: You can decide to delete all documents which meet certain criteria or just a specific one. The corresponding commands for this are “delete_one” and “delete_many”.

“delete_one” example

To delete a MongoDB document with Python, you can do the following:

import pymongo
myclient = pymongo.MongoClient ("<mongodb url="">")</mongodb>
mydb = myclient ["clientlist"]
mycol = mydb [ "clients_unitedstates" ]
myquery = { "address" : "42 Elm Street" }
mycol.delete_one (myquery)

In this example, the entry with the address “42 Elm Street” is deleted. All other entries will remain unchanged.

Example for deleting all entries in a Collection

If you would like to delete all entries in a MongoDB Collection, you can do so with the following:

import pymongo
myclient = pymongo.MongoClient ("<mongodb url="">")</mongodb>
mydb = myclient ["clientlist"]
mycol = mydb [ "clients_unitedstates" ]
x = mycol.delete_many ( { } )
print (x.deleted_count, "documents deleted.")

In this example, all entries in the “clients_unitedstates” Collection are deleted while the Collection itself is kept. You could now add new entries, for example. You can also delete the entire Collection.

We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.