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 } } >
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。