【MongoDB学习笔记8】深入MongoDB的更新(update)操作:修改器$set
MongoDB中文档存入数据库后用update方法更新文档,update方法有两个参数,例如
成都创新互联专注于柞水网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供柞水营销型网站建设,柞水网站制作、柞水网页设计、柞水网站官网定制、小程序开发服务,打造柞水网络公司原创品牌,更为您提供柞水网站排名全网营销落地服务。
update(args1,args2)
args1是指查询文档的条件;
args2是指对查询到的文档进行什么样的修改;
一、文档替换
> joe1= db.post.findOne({"age":20}) { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 20 } > joe1.age=21 21 > db.post.update({"id":1},joe1) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) >
修改后的结果:
> joe1= db.post.findOne({"age":21}) { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 21 } >
二、使用修改器
1.$set修改器
$set用来指定一个字段的值,如果字段不存在就创建;
> db.post.findOne() { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65 }
增加comments的键:
> db.post.update({"id":0}, ... {$set:{"comments":"i love you"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne() { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65, "comments" : "i love you" } >
修改comments键的值:
> db.post.update({"id":0}, {$set:{"comments":"i don't love you"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne() { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65, "comments" : "i don't love you" } >
修改comments的值为数组:
> db.post.update({"id":0}, {$set:{"comments":["i love you","or","i don't love you"]}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne({"id":0}) { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65, "comments" : [ "i love you", "or", "i don't love you" ] } >
删除comments的值:
> db.post.update({"id":0}, {$unset:{"comments":1}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne({"id":0}) { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65 } >
2.修改内嵌文档
> db.post.findOne({"id":0}) { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65, "comments" : { "1" : 1, "2" : 2, "3" : 3 } } > db.post.update({"id":0}, {$set:{"comments.1":4}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne({"id":0}) { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65, "comments" : { "1" : 4, "2" : 2, "3" : 3 } } >
分享题目:【MongoDB学习笔记8】深入MongoDB的更新(update)操作:修改器$set
标题URL:http://azwzsj.com/article/jsgoce.html