首页 > 解决方案 > Python mongoengine select_related(n) 没有达到我的预期

问题描述

我有一个存储在 mongo 中的对象,它有一个引用字段列表。在 restplus 应用程序中,我需要解析这个对象列表并将它们映射到 JSON 文档中以返回给客户端。

# Classes I have saved in Mongo
class ThingWithList(Document):
    list_of_objects = ListField(ReferenceField(InfoHolder))

class InfoHolder(Document):
    thing_id = StringField()
    thing_i_care_about = ReferenceField(Info)

class Info(Document):
    name = StringField()
    foo = StringField()
    bar = StringField()

我发现遍历列表非常慢。我猜是因为每次我取消引用列表中对象的子项时,我都必须进行另一个数据库查询。

简单(但垃圾)的方法:

info_to_return = []    
thing = ThingWithList.get_from_id('thingsId')
for o in list_of_objects:
    info = {
        'id': o.id,
        'name': o.thing_i_care_about.name,
        'foo': o.thing_i_care_about.foo,
        'bar': o.thing_i_care_about.bar
    }
    info_to_return.append(info)
return(info_to_return)

我想我可以通过使用 select_related 来解决这个问题,听起来它应该为我解引用 N 级深,这样我只做一个大的 mongo 调用,而不是每次迭代几次。当我添加

thing.select_related(3)

它似乎没有效果。我是不是误解了这个功能的用途。我还能如何加快查询速度?

标签: pythonmongodbmongoengine

解决方案


推荐阅读