[英]Pymongo:iterating dictionary of a list of dictionary
可以說我收藏了很多這樣的文件:
{"_id": 0,
"name":"John Doe",
"items": [
{"x":5,
"y":8,
"z":9},
{"x":4,
"y":2,
"z":1},
{"x":3,
"y":5,
"z":8}
]
}
我正在使用pymongo將集合提取到名為“ data”的變量中,並嘗試對項目進行迭代以更新一些項目。 我嘗試使用以下代碼打印這些值:
for i in data:
for j in data[i].get("items"):
pprint(j.get("x"))
它給出了一個錯誤:
pymongo.errors.InvalidOperation: cannot set options after executing query
即使我得到了物品,也看不到更改數據的方法。 為什么會發生這種情況?我如何遍歷項目並更改其值?
db查詢怎么樣?
嘗試這樣的迭代:
cursor = db.get_collection('some_collection').find()
for doc in cursor:
for item in doc['items']:
pprint(item.get('x'))
假設您要更改所有x
的值。
for i in data.get('items'):
# to change the values in items
# this will replace all values of key x
i['x'] = new_value
只需為items
鍵分配一個新值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.