mongoDB 更新数据

使用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 })
 
posted @ 2018-01-13 17:47  晴天小猫  阅读(2037)  评论(0编辑  收藏  举报