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
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'
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.