繁体   English   中英

如何使用 pymongo 迭代带有嵌入式文档的 mongo 文档?

[英]How to iterate over a mongo document with an embedded doc using pymongo?

我有看起来像这样的 MongoDB 数据:

{
    "_id" : ObjectId("602ad096f7449063397d41bd"),
    "name" : "1234/1236 Main St",
    "city" : "Indianapolis",
    "state" : "IN",
    "zip" : "46208",
    "total_units" : 2,
    "units" : [ 
        {
            "unit_num" : 1,
            "street" : "1234 Main",
            "bedrooms" : 3,
            "bath" : 1,
            "sqft" : 1225,
            "monthly_rent" : 800,
            "lease_expiration" : "2021-06-30"
        }, 
        {
            "unit_num" : 2,
            "street" : "1236 Main",
            "bedrooms" : 3,
            "bath" : 1,
            "sqft" : 1225,
            "monthly_rent" : 800,
            "lease_expiration" : "2021-07-31"
        }
    ]
}]}

使用 python 和 PyMongo,我试图遍历所有条目,并非所有条目都有多个单位,并返回monthly_rent 和 lease_expiration 值。 这就是我在 shell 中的内容:

db.property.find({active: true}, {_id: 0, name: 1, "street": 1,"units.monthly_rent": 1, "units.lease_expiration": 1}).sort({"units.lease_expiration": 1})

它返回这个:

{
    "name" : "1234/1236 Main St",
    "units" : [ 
        {
            "street" : "1234 Main St",
            "monthly_rent" : 800,
            "lease_expiration" : "2021-06-30"
        }, 
        {
            "street" : "1236 Main St",
            "monthly_rent" : 800,
            "lease_expiration" : "2021-07-31"
        }
    ]
}

在 python 脚本中,我想遍历每个属性和单元并打印出名称、“units.street”、“units.monthly_rent”、“units.lease_expiration”,但我似乎无法让它遍历这些单元大批。 我正在测试这个:

for prop in list(db.mycol.find({})):
        print(prop)
        print(prop["units.monthly_rent"]) 

print(prop) 按预期打印出所有数据,但另一个打印语句给出错误: KeyError: 'units.monthly_rent'

有人可以指出我正确的方向吗?



从下面的评论中添加聚合查询:

db.property.aggregate([
{ $project: { 
    "units": { 
        $filter: { input: "$units", as: "u", 
            cond: { $gte: [ "$$u.unit_num", 0 ] } 
        } } } 
}, 
{ $unwind: "$units" }, 
{ $project: { 
    "street": "$units.street", "
    monthly_rent": "$units.monthly_rent", 
    "lease_expiration": "$units.lease_expiration" } 
} 
])

您必须循环单位并打印unit.monthly_rent

for prop in list(db.mycol.find({})):
        print(prop)
        for unit in list(prop['units']):
            print(unit['monthly_rent'])

你不能做array['monthly_rent']而是你必须做array[0]['monthly_rent']等等

您已经获得了每个元素,然后您可以访问数组中的 object

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM