Python MongoDB- opdatering
Dateer versameling op
U kan 'n rekord, of dokument soos dit in MongoDB genoem word, opdateer deur die update_one()
metode te gebruik.
Die eerste parameter van die update_one()
metode is 'n navraagobjek wat definieer watter dokument om by te werk.
Let wel: As die navraag meer as een rekord vind, word slegs die eerste voorkoms opgedateer.
Die tweede parameter is 'n objek wat die nuwe waardes van die dokument definieer.
Voorbeeld
Verander die adres van "Valley 345" na "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)
Dateer baie op
Om alle dokumente op te dateer wat aan die kriteria van die navraag voldoen, gebruik die update_many()
metode.
Voorbeeld
Werk alle dokumente op waar die adres met die letter "S" begin:
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.")