让我们说我收藏了很多这样的文件:
{"_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
即使我得到了物品,也看不到更改数据的方法。为什么会发生这种情况,我如何遍历项目并更改其值?
答案 0 :(得分:0)
db查询的外观如何?
尝试这样的迭代:
cursor = db.get_collection('some_collection').find()
for doc in cursor:
for item in doc['items']:
pprint(item.get('x'))
答案 1 :(得分:0)
假设您要更改所有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
键分配一个新值。