首页 > 代码库 > mongo数据更新
mongo数据更新
数据更新
简单的做法是删除重新插入
update()函数
语法
db.集合.update(更新条件,新的对象数据(更新操作符),upsert,multi)
upsert如果要更新的数据不存在,则增加一条新的内容(true为增加,false不增加)
multi:是否只更新满足条件的第一条记录,设置为false只更行第一个,true全更新
> db.stu.find({},{"_id":0}) { "name" : "张三", "sex" : "男", "age" : 18, "score" : 70, "address" : "河南" } { "name" : "李四", "sex" : "女", "age" : 20, "score" : 60, "address" : "山东" } { "name" : "王五", "sex" : "男", "age" : 17, "score" : 44, "address" : "江苏" } { "name" : "赵六", "sex" : "男", "age" : 21, "score" : 80, "address" : "山东" } { "name" : "孙七", "sex" : "女", "age" : 23, "score" : 50, "address" : "湖北" } { "name" : "tom", "sex" : "男", "age" : 24, "score" : 20, "address" : "海南" } { "name" : "lucy", "sex" : "女", "age" : 21, "score" : 62, "address" : "浙江" } { "name" : "jack", "sex" : "男", "age" : 20, "score" : 90, "address" : "美国" } { "name" : "smith", "sex" : "男", "age" : 19, "score" : 88, "address" : "美国" } #1.把年龄<20岁的分数更新为60 db.stu.find({"age":{"$lt":20}},{"_id":0}); { "name" : "张三", "sex" : "男", "age" : 18, "score" : 70, "address" : "河南" } { "name" : "王五", "sex" : "男", "age" : 17, "score" : 44, "address" : "江苏" } { "name" : "smith", "sex" : "男", "age" : 19, "score" : 88, "address" : "美国" } db.stu.update({"age":{"$lt":20}},{"$set":{"score":100}},false,false); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) #只修改了一个 db.stu.find({"age":{"$lt":20}},{"_id":0}); { "name" : "张三", "sex" : "男", "age" : 18, "score" : 100, "address" : "河南" } { "name" : "王五", "sex" : "男", "age" : 17, "score" : 44, "address" : "江苏" } { "name" : "smith", "sex" : "男", "age" : 19, "score" : 88, "address" : "美国" } #全部修改 db.stu.update({"age":{"$lt":20}},{"$set":{"score":100}},false,true); db.stu.find({"age":{"$lt":20}},{"_id":0}); { "name" : "张三", "sex" : "男", "age" : 18, "score" : 100, "address" : "河南" } { "name" : "王五", "sex" : "男", "age" : 17, "score" : 100, "address" : "江苏" } { "name" : "smith", "sex" : "男", "age" : 19, "score" : 100, "address" : "美国" } save() db.stu.save({"_id" : ObjectId("592cc2e00be561e9e879bcb5"),"name":‘张三三‘}); 只能根据_id更新
待续
mongo数据更新
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。