【问题标题】:Querying for values of embedded documents in MongoDB with PyMongo使用 PyMongo 查询 MongoDB 中嵌入文档的值
【发布时间】:2021-01-07 08:10:10
【问题描述】:

我在 MongoDB 中有一个类似这样的文档

{
    "_id": 0,
    "cash_balance": 50,
    "holdings": [
        {
            "name": "item1",
            "code": "code1",
            "quantity": 300
        },
        {
            "name": "item2",
            "code": "code2",
            "quantity": 100
        }
    ]
}

我想查询这个特定的文档并获取 holdings 数组中 code 匹配 "code1" 的对象的数量值>。可以假设会有匹配。

data = collection.find_one({"_id": 0, "holdings.code": "code1"}, {"holdings.$.quantity": 1})

{ "_id": 0, "holdings": [{"name": "item1", "code": "code1", "quantity": 300}] }

运行上面的代码给了我这个输出,我可以通过使用得到数量值:

data["holdings"][0]["quantity]

300

但是,这似乎是一种获取单个值的相当迂回的方式。有没有一种方法可以在不获取包含所需对象的持有数组的情况下查询与代码查询匹配的特定键的值?

【问题讨论】:

    标签: python database mongodb pymongo


    【解决方案1】:

    尝试使用 $unwind 的聚合方法。

    $unwind 执行以下操作:

    从输入文档中解构一个数组字段,为每个元素输出一个文档。每个输出文档都是输入文档,其中数组字段的值被元素替换。

    MongoDB documentation for $unwind

    我为你创建了一个playground 示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-20
      • 2016-05-31
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 2021-11-30
      • 2015-08-27
      相关资源
      最近更新 更多