Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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)

2 Answers

0 votes
by (106k points)

To update a Mongo document after inserting it you can use the below-mentioned code:-

mycollection.update_one({'_id':mongo_id}, {"$set": post}, upsert=False)

0 votes
by (108k points)

After inserting the document inside the MongoDB collection, you can update the fields of the document with the help of an update function. Like say, for instance, you have inserted a document inside the collection as follows:

image

Then let suppose you want to update the field named college, then if you want to update only one field then you can use the updateOne() function, you just have to specify the document on which document you want to perform update function. As given in the below image I have updated the college name for the document that is having the name filed as “ABC”. 

image

And if you want to update more fields then you can use updateMany() function, you just have to specify the document that on which you want to perform updation. 

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers

Browse Categories

...