迭代子文档

时间:2012-12-03 17:38:45

标签: python mongodb

我有这种类型的JSON文档:

{ 
  name : 'John',
  age : 30,
  counts : [
    {day : monday, pay : 75, extra : 33} ,
    {day : tuesday, pay : 69, extra : 12} ,
    {day : sunday, pay : 42, extra : 0}  ]
 }

我想迭代它们并执行操作。我创建了一个变量" a"试图迭代:

x = [2, 67, 53, 21, 5, ... ... ]

for i in db.docs.find():
    a = 0
    while a <= len(i['counts']):
        ...
        x.append(i['counts'][a]['extra']) 
        ...
        total = ...
        ...
        a = a + 1
        db.docs.update({'id': i['id']}, {'$set':{"counts.a.total":total}})

如何让Python接受&#34; a&#34;作为列表索引? 谢谢你的帮助。

这是错误消息:

Traceback (most recent call last):
    x.append(i['counts'][a]['extra'])
IndexError: list index out of range

1 个答案:

答案 0 :(得分:0)

你可以使用for循环:

for element in i['counts']:
    ...
    x.append(element['extra'])

如果必须使用while循环,请确保索引严格低于长度。

while a < len(i['counts']):
相关问题