Switch collection in mongoengine for find query

て烟熏妆下的殇ゞ 提交于 2020-01-05 02:21:49

问题


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

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

回答1:


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 example doesn't work inside functions. It gives unboundlocalerror. A simple get around with existing resources is :

To get:

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

Use new_objects.all() to get all objects etc.

To save:

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



回答2:


Although Prachetos Sadhukhan answer works for me, I prefer to get the collection directly, not relying on private _get_collection method:

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


来源:https://stackoverflow.com/questions/26698471/switch-collection-in-mongoengine-for-find-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!