mongodb修改数据语句_mongodb更新操作这节来说说mongodb更新操作,可以使⽤update()函数来对数据进⾏更新。
语法:db.collection.update( criteria, objNew, upsert, multi )
update语法大全update()接受的四个参数含义如下:
criteria : update的查询条件哪些记录需要更新,类似于SQL update语句的where⼦句。
objNew : update的对象和⼀些更新的操作符如$,$inc等等,也可以理解为SQL update语句的set⼦句。
upsert : 如果不存在update的记录,是否插⼊objNew,true为插⼊,默认是false,不插⼊。
multi : 默认是false,只更新到的第⼀条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
注意:multi只对$操作有效。
1. 实例1
> db.mediaCollection.find({"Title" : "Matrix, The"}).toArray()
[
{
"_id" : ObjectId("53548225d85b463e729a2e57"),
"Type" : "DVD",
"Title" : "Matrix, The",
"Released" : 1999,
"Cast" : [
"Keanu Reeves",
"Carry-Anne Moss",
"Laurence Fishburne",
"Hugo Weaving",
"Gloria Foster",
"Joe Pantoliano"
]
}
]
> db.mediaCollection.update({"Title" : "Matrix, The"},{"Type" : "DVD","Title" : "Matrix, The","Released" : 1999,"Genre":"Action"},true)
> db.mediaCollection.find({"Title" : "Matrix, The"}).toArray()
[
{
"Title" : "Matrix, The", "Released" : 1999, "Genre" : "Action"
}
]
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
"_id":ObjectId("53548225d85b463e729a2e57"),
"Type":"DVD",
"Title":"Matrix, The",
"Released":1999,
"Cast":[
"Keanu Reeves",
"Carry-Anne Moss",
"Laurence Fishburne",
"Hugo Weaving",
"Gloria Foster",
"Joe Pantoliano"
]
}
]
&diaCollection.update({"Title":"Matrix, The"},{"Type":"DVD","Title":"Matrix, The","Released":1999,"Genre":"Action"},true) &diaCollection.find({"Title":"Matrix, The"}).toArray()
[
{
"_id":ObjectId("53548225d85b463e729a2e57"),
"Type":"DVD",
"Title":"Matrix, The",
"Released":1999,
"Genre":"Action"
}
]
2. 使⽤save()命令来完成upset操作
语法:
,
{
3
4
5
6
,
{
writeConcern:
}
)
> db.mediaCollection.save( {"Type" : "DVD", "Title" : "Matrix, the", "Released" : "1999", "Genre" : "Action"}) 1
&diaCollection.save({"Type":"DVD","Title":"Matrix, the","Released":"1999","Genre":"Action"})
3. 递增值$inc
$inc允许给⼀个指定的键加上增量,如果该键不存在将创建。
> db.mediaCollection.insert({ "Type" : "Manga", "Title" : "One Piece", "Volumes" : 612,"Read" : 520 })
> db.mediaCollection.update({"Title" : "One Piece"},{$inc:{"Read":5}})
> db.mediaCollection.find({"Title" : "One Piece"}).toArray()
[
{
"_id" : ObjectId("53560b8be0e2e4dd9bb0683d"),
"Type" : "Manga",
"Title" : "One Piece",
"Volumes" : 612,
"Read" : 525
}
]
1
2
8
9
10
11
12
&diaCollection.insert({"Type":"Manga","Title":"One Piece","Volumes":612,"Read":520}) &diaCollection.update({"Title":"One Piece"},{$inc:{"Read":5}})
&diaCollection.find({"Title":"One Piece"}).toArray()
[
{
"_id":ObjectId("53560b8be0e2e4dd9bb0683d"),
"Type":"Manga",
"Title":"One Piece",
"Volumes":612,
"Read":525
}
]
4. $set设定字段值
可以设定任何数据类型。
> db.mediaCollection.find({"Title" : "Matrix, the"}).toArray()
[
{
"_id" : ObjectId("535609c4e0e2e4dd9bb0683c"),
"Type" : "DVD",
"Title" : "Matrix, the",
"Released" : "1999",
"Genre" : "Action"
}
]
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论