Python Driver (PyMongo)

PyMongo is a Python distribution containing tools for working with MongoDB, and is the recommended way to work with MongoDB from Python.



Install PyMongo

Linux/OS X

You can use pip to install:

pip install pymongo


Use MS Windows installers from


Import pymongo

Complete the remainder of this procedure in a Python interactive shell, or other Python environment (e.g. script, module, project).

Import MongoClient from pymongo.

from pymongo import MongoClient

Create a Connection

Use MongoClient to create a connection:

client = MongoClient()

If you do not specify any arguments to MongoClient, then MongoClient defaults to the MongoDB instance that runs on the localhost interface on port 27017.

You can also specify a complete MongoDB URI to define the connection, including explicitly specifying the host and port number. For example, the following creates a connection to a MongoDB instance that runs on and the port of 27017:

client = MongoClient("mongodb://")

Access Database Objects

The first fundamental class of objects you will interact with using pymongo is Database which represents the database construct in MongoDB. Databases hold groups of logically related collections. MongoDB creates new databases implicitly upon their first use.

To assign the database named primer to the local variable db, you can use attribute access, as in the following:

db = client.primer

You can also access databases using dictionary-style access, which removes Python-specific naming restrictions, as in the following:

db = client['primer']

Access Collection Objects

The second fundamental class of objects you will interact using pymongo is Collection, which represents the collection construct in MongoDB. Collections hold groups of related documents.

You can access collection objects directly using dictionary-style or attribute access from a Database object, as in the following examples:


You may also assign the collection object to a variable for use elsewhere, as in the following examples:

coll = db.dataset
coll = db['dataset']

Additional Information

For more information on installation, see