Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to MongoDB atlas cluster with mongoengine

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.

like image 434
Luccas Paroni Avatar asked Dec 03 '22 18:12

Luccas Paroni


1 Answers

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

like image 191
bagerard Avatar answered Dec 15 '22 00:12

bagerard