標籤:blog asc ali mod 使用 col pre 預設 font
使用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 })
mongoDB 更新資料