Linux

Update Mongodb records using Python

Python can be used to update records as well as add new fields in a particular record. In the first update program, let's update an old value. Let us discuss our next program named update1.py.
Python MongoDB Document update
Python MongoDB Document update
Click to view code
The above code updated the record containing ID=2. The code setID=2 to ID=100. Let us check the output below.
Pymongo MongoDB Document update
Python MongoDB Document update Output
You can see the above image, before and after the code run. The ID=2 become ID=100 only one records containing ID=2 has been changed. There is syntax updatemany in Pymongo to update all relevant records. Unfortunately it is not working in new version. Just make one amendment in above code, replace 6th line statement with following line
result = record1.update({'ID':2},{'$set':{'ID':100}},multi=True)
See the code
Python MongoDB update many document
Python MongoDB update many document
Click to view code
Let us check the out-put.
Python MongoDB update many document
Python MongoDB update many document
From output you can see that ID = 2 replaced with ID = 100 in all documents.

In order to update all records you can take advantages of power of Python. I going to present my next code to update many record.
Python MongoDB Document update many
Python MongoDB Document update many
Click to view code
The above code is very simple. The statement cursor = record1.find({"ID":2},{"ID":True,"_id":False}) filters the records to be updated. I hope you can understand the rest of the code.
Let us check the output.
Pymongo MongoDB Document update many output
Python MongoDB Document update Output
The above out-put is presented by code.
Consider a situation in which you have to add one more field. Now, I am going to present the next code named update2.py.
Python MongoDB Document add new field
Python MongoDB Document add new field
Click to view code
The statement result = record1.update({'ID':100},{'$set':{'website':"l4wisdom.com"}}) does the desired task.
Let us the out-put.
Pymongo MongoDB adding field  output
Pymongo MongoDB adding field output
You can see the out-put, New field 'website':"l4wisdom.com" is added.

If you want to remove particular field, to accomplish this, there is operator called $unset. The above code added the new field 'website':"l4wisdom.com" Our next code will remove that field.
Python MongoDB Document removing a field  $unset
Python MongoDB Document removing a field
Click to view code
Let us check the out-put of above code.
Pymongo MongoDB removing field  output
Pymongo MongoDB removing a field
The field 'website':"l4wisdom.com" has been removed.






admin