user8781522
user8781522

Reputation: 81

Pymongo update_one

I have JSON like below

{"city": "New York"}, {"$set": {"city": "Toronto"}}

When I directly give this in the update_one method

database.collection.update_one({"city": "New York"}, {"$set": {"city": "Toronto"}})

it worked great no issues.

But when I assigned to a variable like

temp = {"city": "New York"}, {"$set": {"city": "Toronto"}}
database.collection.update_one(temp)

Which is giving me the below error:

TypeError("update_one() missing 1 required positional argument: 'update'",)

I have used

json.loads(temp)

as well as

json.dumps(temp)

did not work for me? Any Idea.

Upvotes: 2

Views: 3367

Answers (1)

Samuel Dion-Girardeau
Samuel Dion-Girardeau

Reputation: 3180

The problem is that when you do:

database.collection.update_one({"city": "New York"}, {"$set": {"city": "Toronto"}})

you are correctly passing two positional arguments: the first one (corresponding to filter) is {"city": "New York"}, and the second one (corresponding to update) is {"$set": {"city": "Toronto"}}.

However when you do:

temp = {"city": "New York"}, {"$set": {"city": "Toronto"}}
database.collection.update_one(temp)

You are now passing a single positional argument, which is a tuple, hence the error message about the missing argument.

What you need to do is either:

a) Expand the tuple as positional arguments:

temp = {"city": "New York"}, {"$set": {"city": "Toronto"}}
database.collection.update_one(*temp)  # Notice the "*" here

b) Pass multiple positional arguments:

filter, update = {"city": "New York"}, {"$set": {"city": "Toronto"}}  # Tuple expanded here, as two variable
database.collection.update_one(filter, update)

Upvotes: 2

Related Questions