出處: Youtube 彭彭的課程 Python Flask 網站後端開發 – MongoDB 更新資料
實作筆記
更新一筆文件資料
覆蓋或新增欄位$set
這邊想更新name為Nini的password

python碼
#把資料放到資料庫中
db = client.mywebsite #選擇操作mywebsite資料庫
collection = db.users #選擇操作sers集合
#更新集合中的一筆文件資料
result = collection.update_one({
"name":"Nini"
},{
"$set":{
"password":"9888"
}
})
print("符合條件的文件數量",result.matched_count)
print("實際更新的文件數量",result.modified_count)

若是加了一些原本沒有的欄位,那會新增那個欄位


清除欄位$unset
改成unset可把清除欄位


加減數字欄位$inc
這邊想更新name為Nini的password加上2
9888變成10000,要加上2所以填上2,這邊樣要注意格式要是INT,若格式設成string則不能做加減,可用set把string改成int。


乘除數字欄位$mul
同上這邊想更新name為Nini的password乘上2
10000變成20000,要乘上2所以填上2,若要除2的話就填上0.5


更新多筆文件資料
想要撈password是string的“123”的所有資料,並他們設為int的888

result = collection.update_many({
"password":"123"
},{
"$set":{
"password":888
}
})
print("符合條件的文件數量",result.matched_count)
print("實際更新的文件數量",result.modified_count)

