Luccas Paroni
Luccas Paroni

Reputation: 120

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.

Upvotes: 5

Views: 6562

Answers (3)

marcuse
marcuse

Reputation: 3999

When using mongoengine connecting to MongoDB Atlas cluster regardless of using flask-mongoengine you can use the following function:

# Connect to, return database
def db_connect(database):
    db_uri = "mongodb+srv://<username>:<password>@<cluster>.net/?retryWrites=true&w=majority"
    db = connect(database, host=db_uri)
    return db

Where the database variable is a string with the name of the database.

Upvotes: 2

Elias Prado
Elias Prado

Reputation: 1817

I think the way you are placing the URI is wrong in the place of <database_name> you should instead put the name of your cluster such as this:

app.config['MONG_DBNAME'] = '<DB_name>'
app.config['MONGO_URI'] = 'mongodb+srv://<name>:<password>@<cluster_name>.net/<DB_name>?retryWrites=true'

Upvotes: 2

bagerard
bagerard

Reputation: 6364

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

Upvotes: 16

Related Questions