Flask MongoEngine - How to change database?

空扰寡人 提交于 2019-12-05 20:43:51

As you correctly identified, a MongoEngine instance and consequently all the documents (models) created from it are bound to a particular database.

You can (temporarily) change the database used by a document instance to an alias defined in the document's class by calling the switch_db method on the instance:

Post.objects.all().switch('db1').save()

would save all documents in the database db1 if db1 was defined as db_alias in the Post class (otherwise you'll get a ConnectionError).

Alternatively there are a number of ways to make the initial configuration "dynamic" and e.g. respect environment variables:

import os
app['MONGODB_SETTINGS'] = {'db': os.environ.get('DBNAME', 'db2')}

However, from your comment

Our system uses a number of databases to host this model

it seems that what you probably want is Sharding, where MongoDB takes care of distributing a collection over multiple mongod instances on multiple machines. In that case you connect to a mongos instead, which takes care of routing a query to the right shard. The database name is the same on each shard.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!