MongoDB update object rather than insert a new one

Tags: ,

Using collection.insert_one(json_dict)inserts a new collection

Can I do collection.insert_one() on an already existing object so it then updates.

My object will look something like:

"_id":  1,
"name": "Bob"
"Age": "57"

Then under “Age” I want to add "Location": "New York', how’d I do that using PyMongo


I you want to add new field to existing document, you need to update it. There is a function collection.update_one(query, new_values). First argument is query to match existing document and second argument is update document, which will contain update operation. In your case, it would be $set. Read more about update_one here. So, final operation will look like this.

collection.update_one({"_id": 1}, {"$set": {"Location": "New York"}})

It will find document with _id 1 and set Location field or update it if already exists.

Source: stackoverflow