Python MongoDB Update
- Previous Page MongoDB Delete Collection
- Next Page MongoDB Limit
to update the collection
You can use update_one()
method to update the record or document called in MongoDB.
update_one()
The first parameter of the method is the query object, which is used to define the document to be updated.
Note:If the query finds multiple records, only the first matching item is updated.
The second parameter is an object that defines the new value of the document.
Instance
Change the address "Valley 345" to "Canyon 123":
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] myquery = { "address": "Valley 345" } newvalues = { "$set": { "address": "Canyon 123" } } mycol.update_one(myquery, newvalues) #print "customers" after the update: for x in mycol.find(): print(x)
Update Multiple
To update all documents that match the query conditions, please use update_many()
Method.
Instance
Update all documents whose address starts with the letter "S":
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] myquery = { "address": { "$regex": "^S" } } newvalues = { "$set": { "name": "Minnie" } } x = mycol.update_many(myquery, newvalues) print(x.modified_count, "documents updated.")
- Previous Page MongoDB Delete Collection
- Next Page MongoDB Limit