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

2024-04-16 12:34:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下的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,我试图迭代所有条目,并不是所有条目都有多个单元,然后返回每月租金和租约到期值。这就是我在贝壳里的东西:

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\u rent”、“units.lease\u expiration”,但我似乎无法让它遍历单元数组。我正在测试这个:

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

print(prop)按预期打印出所有数据,但另一个print语句给出一个错误: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" } 
} 
])

Tags: namestreetdbmainunitnum单元st
1条回答
网友
1楼 · 发布于 2024-04-16 12:34:15

您必须在单元上循环并打印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']等等

您获得了每个元素,然后可以访问数组中的对象

相关问题 更多 >