Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update a Mongo document after inserting it?

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) 
like image 777
TIMEX Avatar asked Dec 07 '10 02:12

TIMEX


People also ask

How do you update a document?

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.

How do you update if exists otherwise insert new document?

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.

Which operator is used to update documents in MongoDB?

$setOnInsert This operator is used to set the value of a field if an update results in an insert of a document.


1 Answers

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)

like image 66
allait Avatar answered Oct 14 '22 15:10

allait