Menu
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
- 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.
- Add your MongoDB credentials as environment variables to keep them separate than your code.
- Run the workflow.
- Copy over the example code below into a notebook on the running workflow.
Example Notebook
import pymongo
from pymongo.server_api import ServerApi
import os
host = os.environ['host']
password = os.environ['password']
username = os.environ['username']
client = pymongo.MongoClient(f"mongodb+srv://{username}:{password}@{host}/myFirstDatabase?retryWrites=true&w=majority", server_api=ServerApi('1'))
db = client.test
client.server_info()["version"]
'5.0.6'
db = client.sample_database
col = db.sample_collection
col.insert_one({'hello':'JetML'})
x = col.find_one({'hello':'JetML'})
print(x)
client.close()
{'_id': ObjectId('624dea414d63ef918957f1de'), 'hello': 'JetML'}