【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 } } >
本文出自 “缘随心愿” 博客,请务必保留此出处http://281816327.blog.51cto.com/907015/1598398
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。