YouTip LogoYouTip

Python Mongodb Update Document

# Python3.x Python MongoDB Update Document [![Image 6: Python MongoDB](#) Python MongoDB](#) We can use the `update_one()` method in MongoDB to modify records in a document. The first parameter of this method is the query condition, and the second parameter is the field to be modified. If more than one matching record is found, only the first one will be modified. **The test data used in this article is as follows (click the image to view a larger version):*](#) The following example changes the value of the `alexa` field from `10000` to `12345`: ## Example ```python import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient mycol = mydb myquery = { "alexa": "10000" } newvalues = { "$set": { "alexa": "12345" } } mycol.update_one(myquery, newvalues) # Print the modified "sites" collection for x in mycol.find(): print(x) The output after execution is: !(#) The `update_one()` method can only modify the first matched record. To modify all matched records, you can use `update_many()`. The following example will find all `name` fields starting with **F** and modify the `alexa` field of all matched records to **123**: ## Example ```python import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient mycol = mydb myquery = { "name": { "$regex": "^F" } } newvalues = { "$set": { "alexa": "123" } } x = mycol.update_many(myquery, newvalues) print(x.modified_count, "documents modified") The output is: 1 documents modified Check if the data has been modified: !(#) [![Image 10: Python MongoDB](#) Python MongoDB](#)
← Python Mongodb SortPython Mongodb Insert Document β†’