MongoDB中文档存入数据库后用update方法更新文档,update方法有两个参数,例如
update(args1,args2)
args1是指查询文档的条件;
args2是指对查询到的文档进行什么样的修改;
一、文档替换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
> 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 })
>
|
修改后的结果:
1
2
3
4
5
6
7
8
9
10
|
> joe1= db.post.findOne({
"age"
:21})
{
"_id"
:
ObjectId(
"54a530c3ff0df3732bac1680"
),
"id"
: 1,
"name"
:
"joe"
,
"age"
: 21
}
>
|
二、使用修改器
1.$set修改器
$set用来指定一个字段的值,如果字段不存在就创建;
1
2
3
4
5
6
7
|
> db.post.findOne()
{
"_id"
: ObjectId(
"54a530c3ff0df3732bac167f"
),
"id"
: 0,
"name"
:
"joe"
,
"age"
: 65
}
|
增加comments的键:
1
2
3
4
5
6
7
8
9
10
11
12
|
> 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键的值:
1
2
3
4
5
6
7
8
9
10
11
|
> 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的值为数组:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
> 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的值:
1
2
3
4
5
6
7
8
9
10
|
> 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.修改内嵌文档
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
> 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
}
}
>
|
本文转自 bannerpei 51CTO博客,原文链接:http://blog.51cto.com/281816327/1598398,如需转载请自行联系原作者