How to connect to the mongodb-cluster using mongoengine How to connect to the mongodb-cluster using mongoengine mongodb mongodb

How to connect to the mongodb-cluster using mongoengine


I looked dokstring "register_connection" and I found:

:param kwargs: allow ad-hoc parameters to be passed into the pymongo driver

And I use this as:

import osimport sslfrom mongoengine import DEFAULT_CONNECTION_NAME, register_connectionfrom pymongo import ReadPreferencedb_host = os.getenv('DB_HOST', 'localhost')db_port = int(os.getenv('DB_PORT', '27017'))db_name = os.getenv('DB_DATABASE', 'mydatabase')ssl_certfile = os.getenv('SSL_SERTFILE', 'client.pem')ssl_cert_reqs = ssl.CERT_REQUIREDssl_ca_certs = os.getenv('SSL_CA_CERTS', 'mongoCA.pem')db_user = os.getenv('DB_USER', 'myUser')db_pass = os.getenv('DB_PASS', '')ssl_config = {    'ssl': True,    'ssl_certfile': ssl_certfile,    'ssl_cert_reqs': ssl_cert_reqs,    'ssl_ca_certs': ssl_ca_certs}register_connection(alias=DEFAULT_CONNECTION_NAME,                    name=db_name,                    host=db_host,                    port=db_port,                    username=db_user,                    password=db_pass,                    read_preference=ReadPreference.NEAREST,                    authentication_source=db_name,                    **ssl_config)


MongoEngine is base on pymongo. A mongo_url like 'mongodb://user:passwd@ip:port,ip:port/db' work well in MongoEngine and Pymongo.

The code is like this:

from mongoengine import connect, Document, StringFieldconnect('mpc', host='mongodb://mpc:mpc@mongo-1:28010,mongo-2:28010,mongo-3:28010/mpc')class User(Document):    title = StringField(required=True, max_length=200)print User.objects.count()

For more information: http://docs.mongoengine.org/apireference.html


When using mongoengine connecting to MongoDB Atlas cluster you can use the following simplified function:

# Connect to, return databasedef 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.