Pymongo TypeError API: Failure dict

I am writing an API for my software to make it easier to access mongodb.

I have this line:

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

What throws TypeError: Unhashable type: 'dict' .

This function is simply designed to find a document that returns its argument and updates its create_date field.

Why is this error occurring?

+6
source share
2 answers

It's simple, you added extra / red curly braces, try the following:

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

UPD (explanation if you are on python> = 2.7):

The error occurs because python thinks that you are trying to create a set with the notation {} :

A set of classes is implemented using dictionaries. Accordingly, the requirements for the elements of the set are the same as for the dictionary keys; namely, that the element defines both __eq __ () and __hash __ ().

In other words, the elements of the set must be hashed: for example, int , string . And you give it a dict , which is not a hashable and cannot be a collection item.

Also see this example:

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

Hope this helps.

+12
source

I ran into the same problem here and the curly braces are set fine,

 def test(): connectdb = pymongo.MongoClient('localhost', 27017) db = connectdb['SHEET'] collection = db['abc'] collection.update_one({"_id": "1"}, {"$set:", {"Primary_Addr": "192.168.1.1"}}) 

It always shows:

 collection.update_many({"_id": "1"}, {"$set:",{"Primary_Addr":"192.168.1.1"}}) TypeError: unhashable type: 'dict' 
0
source

Source: https://habr.com/ru/post/949551/


All Articles