本文介绍了在mongoengine中切换集合以查找查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've read mongoengine documentation about switching collection to save document. And test this code and it worked successfully:

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中查找保存的文档时根本不起作用.

But the problem is when I want to find saved document in switch collection switch_collection doesn't work at all.

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

推荐答案

mongoengine==0.10.0 mongoengine.context_managers.switch_collection(cls, collection_name)开始在示例中用作"switch_collection(Group,'group1')as Group:"在函数内部不起作用.它给出unboundlocalerror.现有资源的一个简单解决方法是:

As of mongoengine==0.10.0 mongoengine.context_managers.switch_collection(cls, collection_name)used as "with switch_collection(Group, 'group1') as Group:" in the exampledoesn't work inside functions. It gives unboundlocalerror. A simple get around with existing resources is :

获得:

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()

这篇关于在mongoengine中切换集合以查找查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 20:15