AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

Pymongo: Using Python with MongoDB

PARTAGEZ

PyMongo is the best solution if you want to use MongoDB with Python. The clear and user-friendly standard driver library allows you to create and modify your own databases and collections in just a few steps.

What is PyMongo?

Over the past few years, the MongoDB database management system has established itself as a real alternative to MySQL. Its great advantage is to leave the choice of the programming language to represent objects thanks to adapted drivers. PyMongo is thus the official driver for using MongoDB with Python.

Noticed

MongoDB stores data as JSON documents, grouped and indexed into collections for better organization. The various MongoDB commands allow you to retrieve, sort, modify, group or delete data.

How to install PyMongo?

Want to install Pymongo to use the Python driver library to work under MongoDB? So use Python’s PIP package manager. This allows you to install PyMongo at any time on the device or server running MongoDB. Here is the command to use:

python -m pip install pymongo

Pymongo: creating MongoDB databases

After installing PyMongo, connect to MongoDB. For this, use the MongoClient. The correct command looks like this (replace the mention <> by the corresponding connection string):

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

There are three standard databases in MongoDB: local, admin, and config. But if you want to use MongoDB really efficiently with Python, you’ll need additional databases. To create them, just use the “db” shortcut. If the mentioned database already exists, it will be called. If a database with the matching name does not yet exist, MongoDB creates it for you. The command for a new database named “clientlist” looks like this:

To better protect your data, it is possible to set up an authentication procedure at this location. The corresponding data is stored by default in the admin database. Here’s how to insert authentication:

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

Adding collections with PyMongo

Once the database is created, it is easy to add collections to it with PyMongo. The system only takes them into account when they contain documents. To create a new collection in MongoDB with Python, use the following entry:

collection = database ["clients_france"]

Insert database entries with PyMongo

It is now possible to feed this new collection. New documents are posted there and can be consulted, combined or modified as needed. Here is an example document:

InfoClient = {
"nom" : "Martin",
"adresse" : "252 rue des Pyrénées",
"cp" : "75020",
"ville" : "Paris"
}
collection.insert_one(infoclient)

The “insert_many” method also allows you to add several entries at the same time. Each of these entries automatically receives an individual and unique identifier (_id), unique key with which it can be called later. Adding entries in bulk works like this:

InfoClient = [
{
"nom" : "Martin",
"adresse" : "252 rue des Pyrénées",
"cp" : "75020",
"ville" : "Paris"
}
{
"nom" : "Richard",
"adresse" : "27 rue de la Rotonde",
"cp" : "13001",
"ville" : "Marseille"
}
{
"nom" : "Picard",
"adresse" : "18 rue Victor Hugo",
"cp" : "69002",
"ville" : "Lyon"
}
]
collection.insert_many(infoclient)

PyMongo to call the data

Once the data is saved, the goal is to be able to retrieve it easily later. For this, there are several ways, the most practical of which is undoubtedly with MongoDB Find. Here’s how to use it with the example above:

data = collection.find ( { "ville" : "Paris" } )
print (data)
# {
"_id" : ObjectID ("7fe4a462991acf79e22c" ),
"nom" : "Martin", "adresse" : "252 rue des Pyrénées",
"cp" : "75020",
"ville" : "Paris"
}

Edit entries under MongoDB with PyMongo

The data changes over time and it may be necessary to update them. PyMongo offers different options for modifying entries: in addition to modifications made to a specific document, it is possible to modify several or all entries of a specific database or collection. For this, we use the “update_one” and “update_many” methods.

Example with update_one

To illustrate the “update_one” method, let’s do a simple change of address. Suppose therefore that the customer Martin has moved, still in Paris 20. Instead of deleting his registration and then creating it again, it is possible to modify it as follows:

import pymongo
myclient = pymongo.MongoClient ("<mongodb url="">")</mongodb>
mydb = myclient [ "listeclient" ]
mycol = mydb [ "clients_france" ]
myquery = { "adresse" : "252 rue des Pyrénées" }
newvalues = { "$set" : { "adresse" : "12 rue Belgrand" } }
mycol.update_one (myquery, newvalues)
#print "customer" after the update:
for x in mycol.find ():
print (x)

Example with update_many

The “update_many” command allows you to modify all the documents that meet a certain criterion. The following example assigns a new city to all customer entries whose name begins with M:

import pymongo
myclient = pymongo.MongoClient ("<mongodb url="">")</mongodb>
mydb = myclient [ "listeclients" ]
mycol = mydb [ "clients_france" ]
myquery = { "nom" : "$regex" : "^M" }
newvalues = { "$set" : { "ville" : "Lille" } }
x = mycol.update_many (myquery, newvalues)
print (x.modified_count, "documents updated.")

Delete documents with PyMongo

It is also possible to delete documents. The operation is similar to the methods for modifying one entry or several: all you have to do is sort the documents according to one or more criteria to delete them allor delete only one in particular. The corresponding commands are “delete_one” and “delete_many”.

Example with delete_one

To delete a document with PyMongo, here’s how:

import pymongo
myclient = pymongo.MongoClient ("<mongodb url="">")</mongodb>
mydb = myclient [ "listeclients" ]
mycol = mydb [ "clients_france" ]
myquery = { "adresse" : "252 rue des Pyrénées" }
mycol.delete_one (myquery)

In this example, the entry with the address “252 rue des Pyrénées” will be deleted. The other entries remain as they are.

Deleting all documents from a collection with PyMongo

To remove multiple entries from a MongoDB collection with PyMongo, here’s how:

import pymongo
myclient = pymongo.MongoClient ("<mongodb url="">")</mongodb>
mydb = myclient [ "listeclients" ]
mycol = mydb [ "clients_france" ]
x = mycol.delete_many ( { } )
print (x.deleted_count, "documents effacés.")

In this example, all entries in the “clients_france” collection are deleted but the collection itself remains in place. It is always possible to add other entries to it or even delete the entire collection.

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact