How to connect Python to MongoDB

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

If you’re working with data stored in MongoDB, you’ll probably need to access the database from Python. Luckily the MongoDB client library makes this task a simple one, allowing you to connect to MongoDB with just a few lines of code. In this step-by-step tutorial, we’ll explain how to connect Python to MongoDB using the pymongo client library.

Prerequisites

Before we look at any code, it’s important to make sure certain prerequisites are in place. For this task, there are a few key system requirements:

  • Python must be installed on machine or server. Python 3 is recommended, as Python 2 is scheduled for depreciation.

  • You’ll need to have a localhost server running or have remote access to a server using a private key.

  • A MongoDB server must be running on the machine.

  • It’s helpful to have some experience with bash commands and the command prompt.

Install the pymongo client library for MongoDB

Once you’ve confirmed that all the system requirements are in place, it’s time to install the pymongo client library for MongoDB. Run one of the following commands, depending on which version of Python is running on your machine:

1
2
3
4
5
# python 3 installation of pymongo
pip3 install pymongo

# python 2 installation of pymongo
pip install pymongo

Connect to the MongoDB server

Next, we’ll connect to the MongoDB server. On macOS and Linux-based terminals, you can use the ps command to grep for the MongoDB service:

1
ps | grep mongo

On most Linux servers, you can use the service command to start and stop the mongod server:

1
sudo service mongod status

On macOS, you can use the list command to confirm that MongoDB was installed using Homebrew:

1
brew services list

After you’ve confirmed that the MongoDB server is running, you can use the mongo command to enter the Mongo shell:

1
mongo

Adding the --port option allows you to specify the port that MongoDB runs on (the default value for this is 27017):

1
mongod --port 8080

Connect to the Elasticsearch cluster with a client instance

If the pymongo Python module was installed properly, then you should be able to import it without receiving an ImportError. Open the Python 3 interpreter in the terminal or command prompt by typing python3, and try to import the module:

Try to import the pymongo module:

1
2
3
import pymongo
# ..or:
from pymongo import MongoClient

Use Python’s IDLE environment to import and test the MongoDB client module:

Screenshot of the IDLE development environment importing the pymongo Python module and its client

Create a working environment for the pymongo script:

If you don’t already have a script to work with, your next step will be to create a Python script in the HTTP server’s web root directory (usually located at /var/www/html for Apache servers, or the /Volumes directory for a macOS localhost server).

In a UNIX-based terminal, use the touch command to create a new Python script. You can name the script whatever you want, but it needs to have the .py file extension. Our example script will be named mongo_test.py:

1
2
cd /var/www/html
sudo touch mongo_test.py

NOTE: Every programming language has its own unique naming conventions. For Python, script names are generally in lowercase, with underscores (_) instead of hyphens (-) between words.

Edit the Python script and connect to the MongoDB server

Now that you’ve created a Python script, you can edit it and import the MongoClient class from the pymongo MongoDB library at the beginning of the Python script:

1
2
3
4
#!/usr/bin/env python3
#-*- coding: utf-8 -*-

from pymongo import MongoClient

Create a class instance of the MongoDB client:

Next, we’ll instantiate a new client that can be used to make RESTFul API calls:

1
2
# create a new client instance
client = MongoClient()

Instantiate a MongoDB database (pymongo.database.Database) class object:

A Mongo database is represented as a method of the client object, and it can be instantiated in a couple different ways:

1
2
3
4
5
# access the collection directly
dbase = client.pymongo_test

# or access it as a key
dbase = client['pymongo_test']

In both examples, the code is accessing the database sub-collection of the pymongo.database class.

Screenshot of the MongoDB shell and the `pymongo` module in Python's IDLE

Conclusion

Python is a popular programming language, and it’s important to be able to connect to Mongo and access your database from a Python script. With the pymongo client library, accomplishing this task is quick and easy. Using the instructions provided in this article, you’ll have no trouble connecting to MongoDB using Python.

In our tutorial, we looked at the code one section at a time. The complete Python script needed to connect to Mongo and the server’s databases can be seen below:

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python3
#-*- coding: utf-8 -*-

from pymongo import MongoClient

# access the database collection directly
db = client.pymongo_test

# or access it as a key
db = client['pymongo_test']

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.