Let's say I insert the document.
post = { some dictionary }
mongo_id = mycollection.insert(post)
Now, let's say I want to add a field and update it. How do I do that? This doesn't seem to work.....
post = mycollection.find_one({"_id":mongo_id})
post['newfield'] = "abc"
mycollection.save(post)
This is an old question, but I stumbled onto this when looking for the answer so I wanted to give the update to the answer for reference.
The methods
save
andupdate
are deprecated.in the OPs particular case, it's better to use
replace_one
.According to the latest documentation about PyMongo titled Insert a Document (insert is deprecated) and following defensive approach, you should insert and update as follows:
I will use
collection.save(the_changed_dict)
this way. I've just tested this, and it still works for me. The following is quoted directly frompymongo doc.
:save(to_save[, manipulate=True[, safe=False[, **kwargs]]])
In pymongo you can update with:
mycollection.update({'_id':mongo_id}, {"$set": post}, upsert=False)
Upsert parameter will insert instead of updating if the post is not found in the database.
Documentation is available at mongodb site.
UPDATE For version > 3 use update_one instead of update:
mycollection.update_one({'_id':mongo_id}, {"$set": post}, upsert=False)
should work splendidly for you. If there is no document of id
mongo_id
, it will fail, unless you also useupsert=True
. This returns the old document by default. To get the new one, passreturn_document=ReturnDocument.AFTER
. All parameters are described in the API.The method was introduced for MongoDB 3.0. It was extended for 3.2, 3.4, and 3.6.