Docs Menu

Docs HomeDevelop ApplicationsPython DriversPyMongo

Connect to MongoDB

1

Copy and paste the following code into the quickstart.py file in your application:

from pymongo import MongoClient
uri = "<connection string URI>"
client = MongoClient(uri)
try:
database = client.get_database("sample_mflix")
movies = database.get_collection("movies")
# Query for a movie that has the title 'Back to the Future'
query = { "title": "Back to the Future" }
movie = movies.find_one(query)
print(movie)
client.close()
except Exception as e:
raise Exception("Unable to find the document due to the following error: ", e)
2

Replace the <connection string URI> placeholder with the connection string that you copied from the Create a Connection String step of this guide.

3

In your shell, run the following command to start this application:

python3 quickstart.py

The output includes details of the retrieved movie document:

{
_id: ...,
plot: 'A young man is accidentally sent 30 years into the past...',
genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ],
...
title: 'Back to the Future',
...
}

Tip

If you encounter an error or see no output, check whether you specified the proper connection string, and that you loaded the sample data.

After you complete these steps, you have a working application that uses the driver to connect to your MongoDB deployment, runs a query on the sample data, and prints out the result.

Note

If you run into issues on this step, ask for help in the MongoDB Community Forums or submit feedback by using the Rate this page tab on the right or bottom right side of this page.

Next Steps
← Create a Connection String