Let us say I have a big collection including documents such as these:
{"_id": 0,
"name":"John Doe",
"items": [
{"x":5,
"y":8,
"z":9},
{"x":4,
"y":2,
"z":1},
{"x":3,
"y":5,
"z":8}
]
}
I am fetching the collection into a variable called 'data' with pymongo and trying to iterate over the items in order to update some. I have tried to print those values with the following code:
for i in data:
for j in data[i].get("items"):
pprint(j.get("x"))
and it gave an error:
pymongo.errors.InvalidOperation: cannot set options after executing query
Even if I get the items, I do not see a way to change data. Why is this happening and how can I iterate through items and change their values?
How looks db query?
Try something like this for iteration:
cursor = db.get_collection('some_collection').find()
for doc in cursor:
for item in doc['items']:
pprint(item.get('x'))
Let's say if you want to change the values of all 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
simply assign a new value to items
key.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.