Reputation: 182
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
Upvotes: 1
Views: 1787
Reputation: 21295
You can use the update
method with upsert: true
to achieve this.
Normally, update
changes an existing document. But with upsert: true
- if no matching document is found for the update, a new document is created.
Docs: https://docs.mongodb.com/manual/reference/method/db.collection.update/#update-upsert
Upvotes: 0
Reputation: 623
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.
Upvotes: 2