Pymongo API类型错误:不可更改的di

2024-04-25 00:56:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的软件编写一个API,以便更容易访问mongodb。

我有这句台词:

def update(self, recid):        
    self.collection.find_and_modify(query={"recid":recid}, update={{ "$set": {"creation_date":str( datetime.now() ) }}} )

它抛出TypeError: Unhashable type: 'dict'

此函数仅用于查找recid与参数匹配的文档并更新其创建日期字段。

为什么会发生这个错误?


Tags: andselfapi软件mongodbdefupdatefind
1条回答
网友
1楼 · 发布于 2024-04-25 00:56:37

很简单,您已经添加了额外/多余的花括号,请尝试以下操作:

self.collection.find_and_modify(query={"recid":recid}, 
                                update={"$set": {"creation_date": str(datetime.now())}})

UPD(说明,假设您使用的是python>;=2.7):

出现此错误的原因是python认为您正在尝试使用{}符号创建一个集合:

The set classes are implemented using dictionaries. Accordingly, the requirements for set elements are the same as those for dictionary keys; namely, that the element defines both __eq__() and __hash__().

换句话说,集合的元素应该是散列的:例如intstring。你要传递一个dict给它,它是不可散列的,不能是集合的元素。

另外,请参见以下示例:

>>> {{}}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

希望能有所帮助。

相关问题 更多 >