簡體   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