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)
Select the document you want to edit by clicking the document name. On the Document Details page, click EDIT / UPDATE. You can see this button at the top right corner of the page only if you have Document Edit Permission. On the Edit Document page, make your changes.
In order to create a document if it doesn't already exist, you need to pass { upsert : true } in the options hash as it defaults to false . i.e. update is deprecated. Use updateOne, updateMany, or bulkWrite instead.
$setOnInsert This operator is used to set the value of a field if an update results in an insert of a document.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With