> For the complete documentation index, see [llms.txt](https://datalab-docs.datacamp.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://datalab-docs.datacamp.com/connect-to-data/mongodb.md).

# MongoDB

To work with data in a MongoDB database, you first need to create a set of [Environment variables](/work/environment-variables.md) to securely store the connection credentials. Next, you can write some Python code to establish a connection and run queries.

## Store MongoDB credentials

Create a new Python workbook (or duplicate [this workbook](https://app.datacamp.com/workspace/new?_tag=workspace\&title=Connect%20to%20a%20MongoDB%20database\&accountType=personal\&utm_content=copy_duplicate_link\&utm_medium=in_product\&utm_source=workspace\&visibility=public\&workspaceId=b00c0e1a-d0c0-4f7f-a6c9-592dd6143fd8) that already has all the Python code you'll need in the next step).

In your new workbook, click on "Environment", and click on "+" next to "Environment variables". You need to create 3 environment variables:

* `MONGO_HOST`: Where your MongoDB cluster/database is hosted, e.g. test-cluster.t6rcsje.mongodb.net.
* `MONGO_USER`: The username with which to connect to your MongoDB cluster
* `MONGO_PASS`: The username's password.

Give a meaningful name to this set of Environment variables, e.g. "MongoDB Cluster". Click Save and continue until your session is restarted to activate these environment variables.

<figure><img src="https://4179539225-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZqboFGZzD87nn7oPsm%2Fuploads%2F9PuD2IIrDzXxCYP9uY5H%2Fimage.png?alt=media&amp;token=73bc10ee-4717-45d7-925e-b1f0fd5aa057" alt=""><figcaption><p>Set up environent variables.</p></figcaption></figure>

## Query the database

Create a new Python cell and include the following code snippet to create a new Mongo client that connects to the database. Notice how the environment variables are fetched from the environment using `os.environ`.

```python
!pip install pymongo

import os
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi

uri = f'mongodb+srv://{os.environ.get("MONGO_USER")}:{os.environ.get("MONGO_PASS")}@{os.environ.get("MONGO_HOST")}/?retryWrites=true&w=majority'

# Create a new client and connect to the server
client = MongoClient(uri, server_api=ServerApi('1'))
```

You can now run queries! To start, you can do a ping command to verify that the connection works fine:

```python
try:
    client.admin.command('ping')
    print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
    print(e)
```

For a quick overview of what PyMongo enables you to do, check out [this comprehensive tutorial](https://api.mongodb.com/python/3.3.1/tutorial.html). It covers how you can get a database, a collection, find documents, insert documents, and more.

### Limit allowed incoming IP addresses

The network calls from the Python or R sessions will always come from one of three fixed, DataCamp-owned IP addresses. You can lock down your MongoDB instance to only accept these IP addresses:

* `34.194.221.107`
* `34.192.118.171`
* `34.192.199.85`


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://datalab-docs.datacamp.com/connect-to-data/mongodb.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
