首页 > 代码库 > 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数据更新