Python Mongodb Update Document

Python Mongodb Python Mongodb

In MongoDB, we can use theupdate_one()method 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

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["exampledb"] 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)

After execution, the output result is:

update_one()The method can only modify the first matching record. To modify all matching records, you can useupdate_many()。

The following example will find allFbeginning withnamefields, and for all matched records, thealexafield is changed to123:

Example

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["exampledb"] mycol = mydb["sites"] myquery = { "name": { "$regex": "^F" } } newvalues = { "$set": { "alexa": "123" } } x = mycol.update_many(myquery, newvalues) print(x.modified_count, "The document has been modified")

The output result is:

1 文档已修改

Check whether the data has been modified:

Python Mongodb Python Mongodb

Other Extensions