## Connecting to MongoDB

Here’s a quick example of how to connect to MongoDB using JetML workflows. Note that your cluster must be publicly accessible.

##### Workflow Setup

1. Add the pymongo[srv]==4.0.2 package to enable Python to connect to MongoDB. We suggest pinning the pymongo version to 4.0.2 for now, but future versions should work as well.
2. Add your MongoDB credentials as environment variables to keep them separate than your code.
3. Run the workflow.
4. Copy over the example code below into a notebook on the running workflow.

##### Example Notebook

```python
import pymongo
```

```python
from pymongo.server_api import ServerApi
```

```python
import os
```

```python
host = os.environ['host']
```

```python
password = os.environ['password']
```

```python
username = os.environ['username']
```

```python
client = pymongo.MongoClient(f"mongodb+srv://{username}:{password}@{host}/myFirstDatabase?retryWrites=true&w=majority", server_api=ServerApi('1'))
```

```python
db = client.test
```

```python
client.server_info()["version"]
```

```
'5.0.6'
```

```python
db = client.sample_database
```

```python

```

```python
col = db.sample_collection
```

```python

```

```python
col.insert_one({'hello':'JetML'})
```

```python

```

```python
x = col.find_one({'hello':'JetML'})
```

```python

```

```python
print(x)
```

```python

```

```python
client.close()
```

```
{'_id': ObjectId('624dea414d63ef918957f1de'), 'hello': 'JetML'}
```

### [converted by JetML](/content/site-root.html)

[download original notebook .ipynb file](https://raw.githubusercontent.com/jetml/Stable-Diffusion-Weather-App/main/weather-stable-diffusion.ipynb) copy html to clipboard

[Download Notebook File](/content/wp-content/uploads/2023/01/MongoDB%20Demo.ipynb)  
* * *
