如何推入嵌套在字典中的数组?

时间:2013-06-04 12:12:33

标签: python mongodb pymongo

我想创建一个mongodb来存储家庭作业结果,我创建了一个homework,这是一个存储结果的字典'每个主题的数组。

import pymongo

DBCONN = pymongo.Connection("127.0.0.1", 27017)
TASKSINFO = DBCONN.tasksinfo

_name = "john"
taskid = TASKSINFO.tasksinfo.insert(
    {"name": _name,
     "homework": {"bio": [], "math": []}
     })

TASKSINFO.tasksinfo.update({"_id": taskid},
                           {"$push": {"homework.bio", 92}})

当我尝试将一些信息推送到db时,出现了错误:

Traceback (most recent call last):
  File "mongo_push_demo.py", line 13, in <module>
    {"$push": {"homework.bio", 92}})
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.5-py2.7-linux-i686.egg/pymongo/collection.py", line 479, in update
    check_keys, self.__uuid_subtype), safe)
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.5-py2.7-linux-i686.egg/pymongo/message.py", line 110, in update
    encoded = bson.BSON.encode(doc, check_keys, uuid_subtype)
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.5-py2.7-linux-i686.egg/bson/__init__.py", line 567, in encode
    return cls(_dict_to_bson(document, check_keys, uuid_subtype))
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.5-py2.7-linux-i686.egg/bson/__init__.py", line 476, in _dict_to_bson
    elements.append(_element_to_bson(key, value, check_keys, uuid_subtype))
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.5-py2.7-linux-i686.egg/bson/__init__.py", line 466, in _element_to_bson
    type(value))
bson.errors.InvalidDocument: cannot convert value of type <type 'set'> to bson

1 个答案:

答案 0 :(得分:5)

{"$push": {"homework.bio", 92}})

应该是:,而不是,

{'a', 1}是Python中两个元素的集合,这就是你得到错误的原因。