I am using mongoengine with Django and within my project need to connect to two instances of MongoDB while serving single request. It works just fine if I use:
c
@Ricardo at the official documentation theres a section explaining context management (i.e switching databases using the same document: http://mongoengine-odm.readthedocs.org/en/latest/guide/connecting.html#context-managers).
The following code will switch the class User
, originally stored in users-db
to the new database archive-user-db
from mongoengine.context_managers import switch_db
class User(Document):
name = StringField()
meta = {"db_alias": "user-db"}
with switch_db(User, 'archive-user-db') as User:
User(name="Ross").save() # Saves the 'archive-user-db'