在mongoengine中切换集合以查找查询

时间:2014-11-02 10:49:51

标签: python mongodb python-2.7 mongoengine

我已阅读有关切换集合以保存文档的mongoengine文档。并测试此代码并成功运行:

from mongoengine.context_managers import switch_db

class Group(Document):
    name = StringField()

Group(name="test").save()  # Saves in the default db

with switch_collection(Group, 'group2000') as Group:
    Group(name="hello Group 2000 collection!").save()  # Saves in group2000 collection

但问题是当我想在交换机集合switch_collection中找到保存的文档时根本不起作用。

with switch_collection(Group, 'group2000') as GroupT:
    GroupT.objects.get(name="hello Group 2000 collection!")  # Finds in group2000 collection

2 个答案:

答案 0 :(得分:8)

截至mongoengine==0.10.0 mongoengine.context_managers.switch_collection(cls, collection_name) 用作“with switch_collection(Group,'group1')作为Group:”在示例中 在函数内部不起作用。它给出了unboundlocalerror。简单了解现有资源是:

获得:

new_group = Group.switch_collection(Group(),'group1')
from mongoengine.queryset import QuerySet
new_objects = QuerySet(Group,new_group._get_collection())

使用new_objects.all()获取所有对象等。

保存:

group_obj = Group()
group_obj.switch_collection('group2')
group_obj.save()

答案 1 :(得分:0)

尽管Prachetos Sadhukhan答案对我有用,但我更喜欢直接获取集合,而不是依赖于_get_collection私有方法:

from mongoengine import connection
new_group_collection = connection.get_db()['group1']
from mongoengine.queryset import QuerySet
new_objects = QuerySet(Group, new_group_collection)