mongodb$inc和$set的区别是什么[mongodb教程]
1、$inc
这个修改器干什么使的呢?看看下面示例的具体操作后的结果即可知道。
示例文档:{"uid":"201203","type":"1",size:10}
> db.b.insert({"uid":"201203","type":"1",size:10})> db.b.find()
{ "_id" : ObjectId("5003b6135af21ff428dafbe6"), "uid" : "201203", "type" : "1",
"size" : 10 }
> db.b.update({"uid" : "201203"},{"$inc":{"size" : 1}})
> db.b.find()
{ "_id" : ObjectId("5003b6135af21ff428dafbe6"), "uid" : "201203", "type" : "1",
"size" : 11 }
> db.b.update({"uid" : "201203"},{"$inc":{"size" : 2}})
> db.b.find()
{ "_id" : ObjectId("5003b6135af21ff428dafbe6"), "uid" : "201203", "type" : "1",
"size" : 13 }
> db.b.update({"uid" : "201203"},{"$inc":{"size" : -1}})
> db.b.find()
{ "_id" : ObjectId("5003b6135af21ff428dafbe6"), "uid" : "201203", "type" : "1",
"size" : 12 }
得出结论:修改器$inc可以对文档的某个值为数字型(只能为满足要求的数字)的键进行增减的操作。
(这里有个问题:上篇中说到更新默认只对满足条件的记录集中第一个文档进行更新,那么使用$inc修改器之后,还是一样吗?)
2、$set
用来指定一个键并更新键值,若键不存在并创建。来看看下面的效果:
> db.a.findOne({"uid" : "20120002","type" : "3"}){ "_id" : ObjectId("500216de81b954b6161a7d8f"), "desc" : "hello world2!", "num"
: 40, "sname" : "jk", "type" : "3", "uid" : "20120002" }
--size键不存在的场合
> db.a.update({"uid" : "20120002","type" : "3"},{"$set":{"size":10}})
> db.a.findOne({"uid" : "20120002","type" : "3"})
{ "_id" : ObjectId("500216de81b954b6161a7d8f"), "desc" : "hello world2!", "num"
: 40, "size" : 10, "sname" : "jk", "type" : "3", "uid" : "20120002" }
--sname键存在的场合
> db.a.update({"uid" : "20120002","type" : "3"},{"$set":{"sname":"ssk"}})
> db.a.find()
{ "_id" : ObjectId("500216de81b954b6161a7d8f"), "desc" : "hello world2!", "num"
: 40, "size" : 10, "sname" : "ssk", "type" : "3", "uid" : "20120002" }
{ "_id" : ObjectId("50026affdeb4fa8d154f8572"), "desc" : "hello world1!", "num"
: 50, "sname" : "jk", "type" : "1", "uid" : "20120002" }
--可改变键的值类型
> db.a.update({"uid" : "20120002","type" : "3"},{"$set":{"sname":["Java",".net","c++"]}})
> db.a.findOne({"uid" : "20120002","type" : "3"})
{
"_id" : ObjectId("500216de81b954b6161a7d8f"),
"desc" : "hello world2!",
"num" : 40,
"size" : 10,
"sname" : [
"java",
".net",
"c++"
],
"type" : "3",
"uid" : "20120002"
}
对于内嵌的文档,$set又是如何进行更新的内嵌的文档的呢,请看下面的示例:
示例文档:{"name":"toyota","type":"suv","size":{"height":10,"width":5,"length":15}}
> db.c.findOne({"name":"toyota"}){
"_id" : ObjectId("5003be465af21ff428dafbe7"),
"name" : "toyota",
"type" : "suv",
"size" : {
"height" : 10,
"width" : 5,
"length" : 15
}
}
> db.c.update({"name":"toyota"},{"$set":{"size.height":8}})
> db.c.findOne({"name":"toyota"})
{
"_id" : ObjectId("5003be465af21ff428dafbe7"),
"name" : "toyota",
"type" : "suv",
"size" : {
"height" : 8,
"width" : 5,
"length" : 15
}
}
> db.c.update({"name":"toyota"},{"$set":{"size.width":7}})
> db.c.findOne({"name":"toyota"})
{
"_id" : ObjectId("5003be465af21ff428dafbe7"),
"name" : "toyota",
"type" : "suv",
"size" : {
"height" : 8,
"width" : 7,
"length" : 15
}
}
可见:对于内嵌文档在使用$set更新时,使用"."连接的方式。
网,大量的免费MongoDB入门教程,欢迎在线学习!
以上是 mongodb$inc和$set的区别是什么[mongodb教程] 的全部内容, 来源链接: utcz.com/z/525828.html