我正在尝试将 defaultdict 变量写入 MongoDB 中的文档。其他一切都很好,只是没有这个属性,它很奇怪!我正在设置一个相当大的默认字典,称为“域”,它以前曾多次工作过。查看此终端输出:
所以这是我的默认字典:
>>> type(domains)
<type 'collections.defaultdict'>
它相当大,大约 3mb:
>>> sys.getsizeof(domains)
3146008
这是我们将其设置为的文档:
>>> db.AggregateResults.find_one({'date':'20110409'}).keys()
[u'res', u'date', u'_id']
让我们获取该文档的 ID:
>>> myID = db.AggregateResults.find_one({'date':'20110409'})['_id']
>>> myID
ObjectId('50870847f49a00509a000000')
太好了,让我们设置属性:
>>> db.AggregateResults.update({'_id':myID}, {"$set": {'domains':domains}})
>>> db.AggregateResults.find_one({'date':'20110409'}).keys()
[u'res', u'date', u'_id']
诶?没救??
嗯......有什么可以保存的吗?
>>> db.AggregateResults.update({'_id':myID}, {"$set": {'myTest':'hello world'}})
>>> db.AggregateResults.find_one({'date':'20110409'}).keys()
[u'myTest', u'res', u'date', u'_id']
好的...所以它可以很好地保存东西...也许是因为 MongoDB 不喜欢 defaultdicts?咱们试试吧:
>>> myDD = defaultdict(int)
>>> myDD['test'] = 1
>>> myDD
defaultdict(<type 'int'>, {'test': 1})
>>> db.AggregateResults.update({'_id':myID}, {"$set": {'myDD':myDD}})
>>> db.AggregateResults.find_one({'date':'20110409'}).keys()
[u'myTest', u'res', u'date', u'myDD', u'_id']
所以它可以很好地保存defaultdicts,只是不是这个?
这么奇怪!任何想法为什么?
编辑安全=真:
>>> db.AggregateResults.update({'_id':myID}, {"$set": {'domains':domains}}, safe=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/site-packages/pymongo-2.1.1_-py2.6-linux-x86_64.egg/pymongo/collection.py", line 405, in update
_check_keys, self.__uuid_subtype), safe)
File "/usr/lib64/python2.6/site-packages/pymongo-2.1.1_-py2.6-linux-x86_64.egg/pymongo/connection.py", line 796, in _send_message
return self.__check_response_to_last_error(response)
File "/usr/lib64/python2.6/site-packages/pymongo-2.1.1_-py2.6-linux-x86_64.egg/pymongo/connection.py", line 746, in __check_response_to_last_error
raise OperationFailure(error["err"], error["code"])
pymongo.errors.OperationFailure: not okForStorage
这个 GoogleGroup 讨论说这可能是由于键中有句号,但是:
>>> [x for x in domains.keys() if '.' in x]
[]