Easy Tutorial
❮ Python Calculator Python Built In Functions ❯

Python Mongodb Modify Documents

Python Mongodb

We can use the update_one() method in MongoDB to modify records in documents. 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 on the image to view the large version):

The following example changes the value of the alexa field from 10000 to 12345:

Example

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["tutorialprodb"]
mycol = mydb["sites"]

myquery = { "alexa": "10000" }
newvalues = { "$set": { "alexa": "12345" } }

mycol.update_one(myquery, newvalues)

# Output the modified "sites" collection
for x in mycol.find():
  print(x)

The execution output is:

The update_one() method can only modify the first matched record. If you want to modify all matched records, you can use update_many().

The following example finds all name fields starting with F and modifies the alexa field of all matched records to 123:

Example

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["tutorialprodb"]
mycol = mydb["sites"]

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:

Python Mongodb

❮ Python Calculator Python Built In Functions ❯