Is it possible to use a variable as part of the collection name and request another collection based on the name in mongoengine?
For example:
There are 3 collections in my mongoDB
- collection_first
- collection_second
- collection_third
and do a simple for loop, for example:
collection_names = ['first', 'second', 'third']
for name in collection_names:
By the way, I am using mongoengin in Django, how to install model.py of such a script?
class Testing(DynamicDocument):
meta = {'collection' : 'collection_name'}
user_name = StringField(db_field='user_name')
Many thanks.
Update solution.
Define the model in models.py without meta:
class Testing(DynamicDocument):
user_name = StringField(db_field='user_name')
When you call a function, use switch_collection
to switch to the real collection:
def search_in_testing(self, name, **kwargs):
with switch_collection(Testing, 'colection_%s' % (name)):
search_results = Testing.objects(**kwargs)
return search_results
In your code, just call the function in a for loop:
collection_names = ['first', 'second', 'third']
for name in collection_names:
search_results = search_in_testing(name, name=name)
Link: switch_collection in mongoengine