I have a flask application for which I used mongoengine to create the database. But now, I need to connect with MongoDB Atlas' Cluster, but I only could find how to do it with Pymongo:
client = pymongo.MongoClient("mongodb+srv://<username>:<password>@<database-name>.mongodb.net/test?retryWrites=true&w=majority")
db = client.test
I just want some help to connect with this new database.
If you are using flask-mongoengine
, you can connect with a given URI with the following pattern:
from flask import Flask
from flask.ext.mongoengine import MongoEngine
app = Flask(__name__)
# This would usually come from your config file
DB_URI = "mongodb+srv://<username>:<password>@<database-name>.mongodb.net/test?retryWrites=true&w=majority"
app.config["MONGODB_HOST"] = DB_URI
db = MongoEngine(app)
if __name__ == '__main__':
app.run()
If you are using plain mongoengine
, you establish the connection simply like this:
from mongoengine import connect
DB_URI = "mongodb+srv://<username>:<password>@<database-name>.mongodb.net/test?retryWrites=true&w=majority"
connect(host=DB_URI)
This is actually what gets called behind the scene by flask-mongoengine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With