Mykola Kharechko
Mykola Kharechko

Reputation: 3211

switch db with mongoenine

I have an issue with switching my database in mongoengine. I want the following code works as expected:


class Test(Document):
    f1 = StringField()

db_names = ['s' + str(i) for i in range(5)]

for db_name in db_names:
    connect(db_name)
    for i in range(10):
        Test.objects.create(f1=uuid1().hex)
    disconnect(db_name)

I know about context_managers.switch_db and have looked to how to switch database name in mongoengine but in my case it doesn't work. I need to switch my db for all models.

Upvotes: 1

Views: 700

Answers (1)

Abbasov Alexander
Abbasov Alexander

Reputation: 1938

Did you try it?

class Test(Document):
    f1 = StringField()  

db_names = [register_connection('s' + str(i), ... ) for i in range(5)]
for db_name in db_names:
    with switch_db(Test, db_name) as Test:
    for i in range(10):
        Test(f1=uuid1().hex).save()

For more about register_connection see help(register_connection) at console.

Upvotes: 1

Related Questions