bson.errors.InvalidDocument:无法编码对象:True

时间:2014-04-19 11:54:37

标签: python python-2.7 pymongo

使用python在Mongo中插入文档时出错。

document = {u'Status': 'Active',
 u'Installation': {u'IsFrugal': True,  u'IsFeatureSet': True,  u'IsEvolving': True, u'IsAffordable': True}, 
  u'AutoList': [u'IsFeatureSet', u'IsAffordable', u'IsFrugal'] 
}

TraceBack错误是

C:\Python27\lib\site-packages\pymongo-2.5.1_-py2.7-win32.egg\pymongo\collection.
py:357: RuntimeWarning: couldn't encode - reloading python modules and trying ag
ain. if you see this without getting an InvalidDocument exception please see htt
p://api.mongodb.org/python/current/faq.html#does-pymongo-work-with-mod-wsgi
  continue_on_error, self.__uuid_subtype), safe)
Traceback (most recent call last):
  File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "C:\Python27\lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "D:\Office_Drive\RetailReco\contactsnew\rrpython\rcauto.py", line 28, in
<module>
    rceval.AutoProcess()
  File "C:\Python27\lib\site-packages\rrpython-0.1-py2.7.egg\rrpython\automizati
on.py", line 67, in AutoProcess
    self._configdb[RCEVALPMTS].save(tempdict)
  File "C:\Python27\lib\site-packages\pymongo-2.5.1_-py2.7-win32.egg\pymongo\col
lection.py", line 266, in save
    return self.insert(to_save, manipulate, safe, check_keys, **kwargs)
  File "C:\Python27\lib\site-packages\pymongo-2.5.1_-py2.7-win32.egg\pymongo\col
lection.py", line 357, in insert
    continue_on_error, self.__uuid_subtype), safe)
bson.errors.InvalidDocument: Cannot encode object: True

"bson.errors.InvalidDocument: Cannot encode object: True"

当我使用&#34; true&#34; True的实例,它运行良好,但它会插入一个字符串值,我想添加布尔值而不是字符串。

当我尝试插入简单的{&#34; name&#34;:True}时 它的工作很好, 怎么可能? 如果有人能给出解决方案,那么会出错。最受欢迎。

2 个答案:

答案 0 :(得分:0)

通过堆栈跟踪,tempdict可能是值True而不是由于应用程序中其他地方(例如rrpython库)的问题而要插入的数据字典。

答案 1 :(得分:-2)

这仅仅是因为json中没有True之类的东西(或bson,这是mongo中实际使用的格式,但它们密切相关)。无需手动将其更改为'true'字符串,您可以将文档编码为json,然后将其插入mongo:

import json
document = {u'Status': 'Active',
   u'Installation': {u'IsFrugal': True,  u'IsFeatureSet': True,  u'IsEvolving': True, 
   u'IsAffordable': True}, 
   u'AutoList': [u'IsFeatureSet', u'IsAffordable', u'IsFrugal'] 
}
jsonified_document = json.dumps(document)