Connect to MongoDB from Python

Connect to MongoDB from Python 3

Connect to MongoDB from Python code – Follow these steps to connect to your Mongo database from your python code.

1. Install PyMongo

PyMongo supports CPython 3.7+ and PyPy3.7+

PyMongo official documentation recommends using pip

$ python3 -m pip install pymongo
Collecting pymongo
  Downloading pymongo-4.3.3-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (501 kB)
     |████████████████████████████████| 501 kB 346 kB/s
Requirement already satisfied: dnspython<3.0.0,>=1.16.0 in /home/jennifer/anaconda3/lib/python3.8/site-packages (from pymongo) (2.2.1)
Installing collected packages: pymongo
Successfully installed pymongo-4.3.3

if you already have pymongo and want to upgrade, run the line below

$ python3 -m pip install --upgrade pymongo

2. Import MongoClient and create a connection

from pymongo import MongoClient

client = MongoClient()

you can specify the host address and port

from pymongo import MongoClient
host = 'localhost'
port = 27017
client = MongoClient(host, port)

You can also use mongodb URI format

from pymongo import MongoClient
URI = 'mongodb://localhost:27017'
client = MongoClient(URI)

MongoDB URI with username and password

URI = 'mongodb://USER:PASSWORD@HOST/DATABASE'

If the username and password have special characters, we can escape them according to RFC 3986 using urllib.parse.quote_plus

from pymongo import MongoClient
from urllib.parse import quote_plus as urlquote

user = 'mongouser'
password = 'mongo@strong!pasword'
host = 'localhost'
port = 27017
URI = f'mongodb://{urlquote(user)}:{urlquote(password)}@{host}:{port}'
client = MongoClient(URI)

3. Close Connection

client.close()

Subscribe to get machine learning tips in your inbox.

Jennifer
Jenniferhttps://jenniferkwentoh.com/about
My name is Jennifer Chiazor Kwentoh, and I am a Machine Learning Engineer. I build production-ready machine learning systems. When I'm not burning out my GPUs, I spend time painting beautiful portraits.

Explore

Up Next

Discover

Other Articles