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 col­lec­tions can be done in just a few steps.

What’s behind PyMongo?

The No-SQL database man­age­ment system MongoDB has developed into a reliable al­tern­at­ive to MySQL in the last few years. What’s more is that with the right drivers, you can use your pro­gram­ming 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 clas­si­fic­a­tion within Col­lec­tions. 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 in­stalling PyMongo, you can connect to MongoDB, using Mon­go­Cli­ent to do this. You can do this with the following command (replace the place­hold­er ‘<<MongoDB URL>>’ with the relevant con­nec­tion 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 ef­fect­ively with Python when you will need ad­di­tion­al databases. You can easily create them using the ab­bre­vi­ation ‘db’. If the named database already exists, it will be opened. If there is no database with the cor­res­pond­ing 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 au­then­tic­a­tion process at this point. The cor­res­pond­ing data are then stored in the ‘admin’ database as standard. You can set up au­then­tic­a­tion as follows:

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

Add Col­lec­tions with PyMongo

As soon as you have created a database, you can easily add Col­lec­tions. However, these will only actually be taken into con­sid­er­a­tion by the system when they contain documents. To create a new Col­lec­tion in MongoDB with Python, you can use the following entry:

collection = database ["clients_unitedkingdom"]

Add MongoDB database entries with Python

You can now fill these new Col­lec­tions 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 Example Street",
"ZIP" : "20097",
"city" : "Manchester"
}
collection.insert_one(clientInfo)

You can add multiple entries at the same time by using ‘insert_many’. Each one of these entries will be auto­mat­ic­ally assigned a unique ‘_id’ field allowing it to be selected and used in­di­vidu­ally later. You can use ‘insert many’ as follows:

clientInfo =[
{
"name" : "Smith",
"address" : "10 Example Street",
"ZIP" : "20097",
"city" : "Manchester"
}
{
"name" : "Jones",
"address" : "1 Wide Alley",
"ZIP" : "10315",
"city" : "London"
}
{
"name" : "Singh",
"address" : "42 Shakespeare Street",
"ZIP" : "44866",
"city" : "Leeds"
}
]
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" : "Manchester" } )
print (data
# {
"_id" : ObjectID ("7fe4a462991acf79e22c" ),
"name" : "Smith", "address" : "10 Main Street",
"ZIP" : "20097",
"city" : "Manchester"
}

Change MongoDB entries with Python

Data can change over time. This means it might be necessary to change MongoDB entries. The com­bin­a­tion of MongoDB and Python gives you several options to amend your entries. Alongside changes to a single document, you can also make amend­ments to more or all entries in a database or a par­tic­u­lar Col­lec­tion. Some suitable methods include, amongst others, ‘update_one’ and ‘update_many’.

‘Update_one’ example

To give you an il­lus­tra­tion 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 com­pletely 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_unitedkingdom" ]
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_unitedkingdom" ]
myquery = { "name" : "$regex" : "^M" }
newvalues = { "$set" : { "city" : "Liverpool" } }
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 cor­res­pond­ing 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_unitedkingdom" ]
myquery = { "address" : "42 Shakespeare Street" }
mycol.delete_one (myquery)

In this example, the entry with the address ‘42 Shakespeare Street’ is deleted. All other entries will remain unchanged.

Example for deleting all entries in a Col­lec­tion

If you would like to delete all entries in a MongoDB Col­lec­tion, you can do so with the following:

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

In this example, all entries in the ‘clients_unitedk­ing­dom’ Col­lec­tion are deleted while the Col­lec­tion itself is kept. You could now add new entries, for example. You can also delete the entire Col­lec­tion.

Go to Main Menu