简体   繁体   English

Pymongo:字典列表的迭代字典

[英]Pymongo:iterating dictionary of a list of dictionary

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. 我正在使用pymongo将集合提取到名为“ data”的变量中,并尝试对项目进行迭代以更新一些项目。 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? db查询怎么样?

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 . 假设您要更改所有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. 只需为items键分配一个新值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM