How to use multiple databases with Flask-MongoEngine

Sometimes it’s a good idea to use different databases for different parts of the application, they can have different requirements for performance and backup strategy or as a step to split a monolith to microservices.

Here is an example of configuration for Flask and MongoEngine.

MONGODB_STATS_ALIAS = "my_db2"

MONGODB_SETTINGS = [
    {
     "ALIAS": "default",
     "DB":    'my_db1',
     "HOST": os.environ.get('MONGODB1_HOST', 'localhost'),
     "PORT": int(os.environ.get('MONGODB1_PORT', 27017))
    },
    {
     "ALIAS": MONGODB_STATS_ALIAS,
     "DB": 'my_db2',
     "HOST": os.environ.get('MONGODB2_HOST', 'localhost'),
     "PORT": int(os.environ.get('MONGODB2_PORT', 27017))
    },
]

class Stats(Document):
	...

    meta = {
        'indexes': [...],
        'db_alias': MONGODB_STATS_ALIAS
    }
comments powered by Disqus