【问题标题】:Retrieving a document where one of its reference fields fulfill a condition检索其中一个参考字段满足条件的文档
【发布时间】:2023-03-13 12:30:01
【问题描述】:

我正在尝试根据其中一个字段的条件从子文档中检索 id。以下是文档架构。

class father(DynamicDocument):
    name = StringField

class child(DynamicDocument):
    name = StringField
    parent = ReferenceField('father')

我如何获得父亲名字为“Anakin”的孩子的 id?

我正在尝试这个查询:

Child.objects.filter(parent__name=Father.objects(name='Anakin').first().id).first().id

但结果是:

mongoengine.errors.InvalidQueryError: Cannot perform join in mongoDB: parent__name

【问题讨论】:

    标签: python mongoengine


    【解决方案1】:

    由于 MongoDB 没有连接,因此无法在 1 个查询中执行此操作。

    使用 MongoEngine 执行此操作的推荐方法是使用 2 个查询:

    anakin = Father.objects(name='Anakin').first()
    anakin_childs = Child.objects.filter(parent=anakin) #.first() if you are only interested in first match
    

    CachedReferenceField 您可能也感兴趣,它缓存(即重复)父集合中的一些属性,允许您进行此类“加入”。但由于保持缓存属性与原始文档同步的开销,它会降低性能。

    【讨论】:

    • 我同意。正如你所说,我也尝试了两个查询,但它不能达到我想要的目的。我使用了嵌入文档字段的解决方法,它最近似乎工作得更好,时间会证明。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 2021-01-07
    • 1970-01-01
    相关资源
    最近更新 更多