使用db.表名.update() 進行更新數據 指定的表必須是存在的
語法如下:
db.collection.update( criteria, objNew, upsert, multi )
criteria : update的查詢條件,類似sql update查詢內where后面的
objNew : update的對象和一些更新的操作符(如$,$inc...)等,也可以理解為sql update查詢內set后面的
upsert : 這個參數的意思是,如果不存在update的記錄,是否插入objNew,true為插入,默認是false,不插入。
multi : mongodb默認是false,只更新找到的第一條記錄,如果這個參數為true,就把按條件查出來多條記錄全部更新。
例如我們有一張表是 noPK
> db.noPK.find()
{ "_id" : ObjectId("5a50642b908e6b07a84472a2"), "name" : "javascript", "value" : "vue.js" }
{ "_id" : ObjectId("5a50655b908e6b07a84472a3"), "name" : "python", "type" : "script" }
我們需要將name的值是python的更新為shell
需要注意是mongo是區分大小寫的當你把python 寫錯成Python 是無法更新數據的
> db.noPK.update({"name":"Python"}, {$set:{"name":"shell"}})
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
>
返回的結果顯示更新條目是0 是因為寫錯成Python
> db.noPK.update({"name":"python"}, {$set:{"name":"shell"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.noPK.find()
{ "_id" : ObjectId("5a50642b908e6b07a84472a2"), "name" : "javascript", "value" : "vue.js" }
{ "_id" : ObjectId("5a50655b908e6b07a84472a3"), "name" : "shell", "type" : "script" }
>
mongoDB 更新是默認只更新匹配到的第一條數據
如果我們想更新所有的匹配到的數據,則multi 要設置為true
例如:我們的noPk 表 有3個name 都是shell
> db.noPK.find()
{ "_id" : ObjectId("5a50642b908e6b07a84472a2"), "name" : "javascript", "value" : "vue.js" }
{ "_id" : ObjectId("5a50655b908e6b07a84472a3"), "name" : "shell", "type" : "script" }
{ "_id" : ObjectId("5a506b40908e6b07a84472a4"), "name" : "shell", "type" : "script" }
{ "_id" : ObjectId("5a506b9d908e6b07a84472a5"), "name" : "shell", "type" : "script", "script_type" : "bash_shell" }
>
我們要全部更新他們
> db.noPK.update({"name":"shell"}, {$set:{"name":"Xshell"}}, false, true)
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })