Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python MongoDB Update Documents

Python MongoDB Update Documents

Python Mongodb Python Mongodb

We can use the update_one() method in MongoDB to modify records in a document. The first parameter is the query condition, and the second parameter is the field to modify.

If more than one matching record is found, only the first one is modified.

The test data used in this article is as follows (click the image to view full size):

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

Example

import

pymongo

myclient

=

pymongo

.

MongoClient

(

"

mongodb://localhost:27017/

"

)

mydb

=

myclient

[

"

runoobdb

"

]

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 only modifies the first matched record; to modify all matched records, use update_many().

The following example finds all documents whose F field starts with name field, and sets the alexa field of all matched records to 123:

Example

import

pymongo

myclient

=

pymongo

.

MongoClient

(

"

mongodb://localhost:27017/

"

)

mydb

=

myclient

[

"

runoobdb

"

]

mycol

=

mydb

[

"

sites

"

]

myquery

= {

"

name

"

: {

"

$regex

"

:

"

^F

"

} }

newvalues

= {

"

$set

"

: {

"

alexa

"

:

"

123

"

} }

x

=

mycol

.

update_many

(

myquery

,

newvalues

)

print

(

x

.

modified_count

,

"

Document modified

"

)

The output is:

1 文档已修改

Check whether the data has been modified:

Python Mongodb Python Mongodb