We have already inserted and consulted documents with Pymongo, in this example we are going to see how we can update a document with Pymongo.
First of all, import the Pymongo library into our program
from pymongo import MongoClient
client = MongoClient()
Using the MongoClient we will establish the connection with the database MongoDB. Once established, we must select which database and collection we are going to use.
db = client.test
users = db.users
In the code we can verify that the database to be used is test and that the collection is called users.
To be able to update a document with Pymongo we have two alternatives, on the one hand there is updating the first document in the collection that matches the searched one, in this case we have the update_one() method or updating all the documents in the collection that match the searched structure, in this case we must use the update_many() method
The structure of both methods is as follows:
collection.update_one(searched_document,update_operator)
The first thing will be to create a document that contains the minimum data of the documents to be updated. For example, we want to update all people who are 30 years old. In this case the document will be:
doc = {
age: 30
}
Or we may want to update all those documents of people who are 30 years old and called ‘Pilar’.
doc = {
age: 30,
'name': 'Pilar'
}
We can add the attributes we want in the search document.
The second attribute of the update_one() and update_one() methods must be a document that contains an update operator: $set, $pull, $push,…
This update operator will add, update or remove information from some of the document properties.
For example, if we want to update the age property, previously searched, and indicate that the age is now 31, we will write the following:
{"$set": {"age":31}})
We will only have to execute the update_one() or update_many methods.
result = users.update_many(olduser,{"$set": {"age":31}})
In the result variable there is information related to the result obtained, specifically it leaves us the variable modified_count with the number of documents that have been updated.
We can see the effect of updating a document with Pymongo by writing:
print 'Number of modified documents ' + str(result.modified_count)
