是否可以使用变量作为集合名称的一部分,并根据mongoengine中的名称查询不同的集合?
例如:
我的mongoDB中有3个集合
并执行一个简单的for循环,如:
collection_names = ['first', 'second', 'third']
for name in collection_names:
## Query the collection_+`name` here
顺便说一句,我在Django中使用mongoengin,如何设置这种场景的model.py?
class Testing(DynamicDocument):
# The collection_name should be dynamic, isn't it?
meta = {'collection' : 'collection_name'}
user_name = StringField(db_field='user_name')
非常感谢。
更新解决方案。
在models.py中定义Model而不使用meta:
class Testing(DynamicDocument):
## Do NOT use the meta to point to a specific collection.
user_name = StringField(db_field='user_name')
调用此函数时,请使用switch_collection
切换到真实集合:
def search_in_testing(self, name, **kwargs):
with switch_collection(Testing, 'colection_%s' % (name)):
search_results = Testing.objects(**kwargs)
return search_results
在你的代码中,只需在for循环中调用该函数:
collection_names = ['first', 'second', 'third']
for name in collection_names:
search_results = search_in_testing(name, name=name)
答案 0 :(得分:1)
或许 commit 中的以下测试会在某种程度上有所帮助:
def test_dynamic_collection_naming(self)
def create_collection_name(cls):
return "PERSON"
class DynamicPerson(Document):
name = StringField()
age = IntField()
meta = {'collection': create_collection_name}
collection = DynamicPerson._get_collection_name()
self.assertEquals(collection, 'PERSON')
DynamicPerson(name='Test User', age=30).save()
self.assertTrue(collection in self.db.collection_names())
答案 1 :(得分:0)
是的,你可以这样做。例如,
for name in collection_names:
for doc in db[collection_+'name'].find():
print doc
这里db是Database
对象。