Python & MongoDB

The MongoClient is a class that helps you interact with MongoDB. First, we import MongoClient from pymongo, which is an official MongoDB driver for Python.

Install Package


  • python3 -m pip install pymongo

Create MongoDB Instance


  • Create MongoDB instance on the cloud
  • Save Username & password from connection Tab
# Install package
python3 -m pip install pymongo

...
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.4/1.4 MB 26.9 MB/s eta 0:00:00
Collecting dnspython<3.0.0,>=1.16.0
  Downloading dnspython-2.7.0-py3-none-any.whl (313 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 313.6/313.6 KB 43.7 MB/s eta 0:00:00
Installing collected packages: dnspython, pymongo
Successfully installed dnspython-2.7.0 pymongo-4.10.1

# Save username and password from connection tab to use in python
us: root
pw: EUgxNucVHylURid2XYLaeTp8

Create Python File


  • create a connection file, name it: mongo_connect.py
# Save this code in the mongo_connect.py file
from pymongo import MongoClient
user = 'root'
password = 'EUgxNucVHylURid2XYLaeTp8' 
host='mongo'
#create the connection url
connecturl = "mongodb://{}:{}@{}:27017/?authSource=admin".format(user,password,host)

# connect to mongodb server
print("Connecting to mongodb server")
connection = MongoClient(connecturl)

# get database list
print("Getting list of databases")
dbs = connection.list_database_names()

# print the database names

for db in dbs:
    print(db)
print("Closing the connection to the mongodb server")

# close the server connecton
connection.close()

Execute File

  • Let’s test our connection file to see if it works
  • python3 mongo_connect.py
# Test connection file
~$ python3 mongo_connect.py

# OUTPUT
Connecting to mongodb server
Getting list of databases
admin
config
local
Closing the connection to the mongodb server

Access Documents


Query DB

Let’s use python to access the DB and manipulate the documents

  • Open a new python file and save it as: mongo_query.py
  • connect to the mongodb server.
  • select a database named training.
  • select a collection named python.
  • insert a sample document.
  • query all the documents in the training database and python collection.
  • close the connection to the server.
from pymongo import MongoClient
user = 'root'
password = 'EUgxNucVHylURid2XYLaeTp8'
host='mongo'
#create the connection url
connecturl = "mongodb://{}:{}@{}:27017/?authSource=admin".format(user,password,host)

# connect to mongodb server
print("Connecting to mongodb server")
connection = MongoClient(connecturl)

# select the 'training' database 
db = connection.training

# select the 'python' collection 
collection = db.python

# create a sample document
doc = {"lab":"Accessing mongodb using python", "Subject":"No SQL Databases"}

# insert a sample document
print("Inserting a document into collection.")
db.collection.insert_one(doc)

# query for all documents in 'training' database and 'python' collection
docs = db.collection.find()

print("Printing the documents in the collection.")

for document in docs:
    print(document)

# close the server connecton
print("Closing the connection.")
connection.close()

Execute File

  • python3 mongo_query.py
~$ python3 mongo_query.py

# OUTPUT
Connecting to mongodb server
Inserting a document into collection.
Printing the documents in the collection.
{'_id': ObjectId('671826d0364e49e111edf7a6'), 'lab': 'Accessing mongodb using python', 'Subject': 'No SQL Databases'}
Closing the connection.

Insert into DB


Using the same db as above let’s write a python program that will:

  • connect to the mongodb server.
  • select a database named training.
  • select a collection named mongodb_glossary.
  • insert the following documents into the collection mongodb_glossary.
{“database”:”a database contains collections”}

{“collection”:”a collection stores the documents”}

{“document”:”a document contains the data in the form of key value pairs.”}
  • query and print all the documents in the training database and mongodb_glossary collection.
  • close the connection to the server.
from pymongo import MongoClient
user = 'root'
password = 'MjQwOTgtcnNhbm5h' # CHANGE THIS TO THE PASSWORD YOU NOTED IN THE EARLIER EXCERCISE - 2
host='mongo'
#create the connection url
connecturl = "mongodb://{}:{}@{}:27017/?authSource=admin".format(user,password,host)

# connect to mongodb server
print("Connecting to mongodb server")
connection = MongoClient(connecturl)

# select the 'training' database 

db = connection.training

# select the 'python' collection 

collection = db.mongodb_glossary

# create documents

doc1 = {"database":"a database contains collections"}
doc2 = {"collection":"a collection stores the documents"}
doc3 = {"document":"a document contains the data in the form or key value pairs."}

# insert documents
print("Inserting documents into collection.")

db.collection.insert_one(doc1)
db.collection.insert_one(doc2)
db.collection.insert_one(doc3)

# query for all documents in 'training' database and 'python' collection

docs = db.collection.find()

print("Printing the documents in the collection.")

for document in docs:
    print(document)

# close the server connecton
print("Closing the connection.")
connection.close()