Python MongoDB Update

Update Collection – Цуглуулга шинэчлэх  #

You can update a record, or document as it is called in MongoDB, by using the update_one() method.

Та MongoDB-д бичиг баримт (эсвэл MongoDB-д нэрлэгдсэнээр баримт бичиг) шинэчлэхийн тулд update_one() аргыг ашиглаж болно.

The first parameter of the update_one() method is a query object defining which document to update.

update_one() аргын эхний параметр нь шинэчлэх баримт бичгийг тодорхойлох асуулгын объект юм.

Note: If the query finds more than one record, only the first occurrence is updated.

Тэмдэглэл: Хэрэв асуулгын дагуу нэгээс олон бүртгэл олдвол зөвхөн эхний тохиолдлыг шинэчилнэ.

The second parameter is an object defining the new values of the document.

Хоёр дахь параметр нь баримт бичгийн шинэ утгыг тодорхойлсон объект юм.

Example – Жишээ #

Change the address from “Valley 345” to “Canyon 123”:

“Valley 345” гэсэн хаягийг “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 Many – Олныг шинэчлэх #

To update all documents that meets the criteria of the query, use the update_many() method.

Тохирох шалгуурыг хангаж буй бүх баримт бичгийг шинэчлэхийн тулд update_many() аргыг ашиглана.

Note: If the query finds more than one record, only the first occurrence is updated.

Тэмдэглэл: Хэрэв асуулгын дагуу нэгээс олон бүртгэл олдвол зөвхөн эхний тохиолдлыг шинэчилнэ.

The second parameter is an object defining the new values of the document.

Хоёр дахь параметр нь баримт бичгийн шинэ утгыг тодорхойлсон объект юм.

Example – Жишээ #

Update all documents where the address starts with the letter “S”:

Хаяг дах бүх “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.")

Powered by BetterDocs

Leave a Reply