【问题标题】:Mongoengine how to retrieve filtered subdocuments in an EmbeddedDocumentListField in a collectionMongoengine如何在集合中的EmbeddedDocumentListField中检索过滤的子文档
【发布时间】:2019-11-19 01:14:02
【问题描述】:

我有一个文档模型如下:

class MyDocumentModel(DynamicDocument):
    subdocuments = EmbeddedDocumentListField(MySubdocumentModel)

class MySubdocumentModel(EmbeddedDocument):
    some_field = StringField()

我想要做的是通过在some_field 上过滤subdocuments 来获取整个集合中MyDocumentModel 文档中包含的所有MySubdocumentModel 嵌入文档的列表。有谁知道这是否可能/如何在mongoengine 中实现?到目前为止,我的研究还没有产生任何有效的结果。

我尝试过的事情:

MyDocumentModel.objects(subdocuments__some_field="my_field_value")
MyDocumentModel.objects(subdocuments__match={"some_field": "my_field_value"})

任何建议将不胜感激。

【问题讨论】:

    标签: python mongodb mongodb-query aggregation-framework mongoengine


    【解决方案1】:

    通过一些额外的搜索和试验,我发现你可以做到这一点:

    subdocs = MyDocumentModel._get_collection().aggregate([
                {"$unwind": "$subdocuments"},
                {"$match": {'subdocuments.some_field':'my_field_value'}}
              ])
    

    我希望这可以帮助其他需要做类似事情的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      相关资源
      最近更新 更多