mongoDB中文档存入数据库后用update方法更新文档,update方法有两个参数,例如update(args1,args2)args1是指查询文档的条件;args2是指对查询到的文档进行什么样的修改;
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
}
}
>
--结束END--
本文标题: 【MongoDB学习笔记8】深入MongoDB的更新(update)操作:修改器$set
本文链接: https://lsjlt.com/news/46818.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0