mongo数据更新

Posted 梦想远航

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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数据更新的主要内容,如果未能解决你的问题,请参考以下文章

Mongoose/Mongo:更新不保存

Mongo - 通过_id更新嵌套的对象数组

Mongo基于一张表的数据更新另一张表

如何使用查找和更新编写 mongo 请求

mongo更新的基本方法

想要使用 SharePreferences 更新第二个片段中的数据,但第二个片段没有更新