标签:
对于文档的更新除替换外,针对某个或多个文档只需要部分更新可使用原子的更新修改器,能够高效的进行文档更新。更新修改器是中特殊的键,
用来指定复杂的操作,比如增加、删除或者调整键,还可能是操作数组或者内嵌文档。
1.$inc
> db.b.insert({"uid":"201603","type":"1","size":10})
WriteResult({ "nInserted" : 1 })
> db.b.find()
{ "_id" : ObjectId("56f3554d7a84d5a96555d7e5"), "uid" : "201603", "type" : "1",
"size" : 10 }
> db.b.update({"uid":"201603"},{"$inc":{"size":5}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.b.find()
{ "_id" : ObjectId("56f3554d7a84d5a96555d7e5"), "uid" : "201603", "type" : "1",
"size" : 15 }
> db.b.update({"uid":"201603"},{"$inc":{"size":2}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.b.find()
{ "_id" : ObjectId("56f3554d7a84d5a96555d7e5"), "uid" : "201603", "type" : "1",
"size" : 17 }
> db.b.update({"uid":"201603"},{"$inc":{"size":-7}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.b.find()
{ "_id" : ObjectId("56f3554d7a84d5a96555d7e5"), "uid" : "201603", "type" : "1",
"size" : 10 }
得出结论:修改器$inc可以对文档的某个值为数字型(只能为满足要求的数字)的键进行增减的操作。
(这里有个问题:上篇中说到更新默认只对满足条件的记录集中第一个文档进行更新,那么使用$inc修改器之后,还是一样吗?)
2.$set
①--结合上边的例子,没有sname的情况:
> db.b.update({"uid":"201603"},{"$set":{"sname":"ssk"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.b.find()
{ "_id" : ObjectId("56f3554d7a84d5a96555d7e5"), "uid" : "201603", "type" : "1",
"size" : 10, "sname" : "ssk" }
②--有sname的情况:
> db.b.update({"uid":"201603"},{"$set":{"sname":"mongo"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.b.find()
{ "_id" : ObjectId("56f3554d7a84d5a96555d7e5"), "uid" : "201603", "type" : "1",
"size" : 10, "sname" : "mongo" }
③--修改键的值的类型:
> db.b.update({"uid":"201603"},{"$set":{"sname":["mongo","redies","mysql"]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.b.find()
{ "_id" : ObjectId("56f3554d7a84d5a96555d7e5"), "uid" : "201603", "type" : "1",
"size" : 10, "sname" : [ "mongo", "redies", "mysql" ] }
>
④--对于内嵌
首先通过$set将sname键修改为内嵌形式
> db.b.update({"uid":"201603"},{"$set":{"sname":{"height":10,"width":20,"length"
:30}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.b.find({"uid":"201603"}).pretty()
{
"_id" : ObjectId("56f3554d7a84d5a96555d7e5"),
"uid" : "201603",
"type" : "1",
"size" : 10,
"sname" : {
"height" : 10,
"width" : 20,
"length" : 30
}
}
> db.b.update({"uid":"201603"},{"$set":{"sname.height":5,"sname.width":15}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.b.find({"uid":"201603"}).pretty()
{
"_id" : ObjectId("56f3554d7a84d5a96555d7e5"),
"uid" : "201603",
"type" : "1",
"size" : 10,
"sname" : {
"height" : 5,
"width" : 15,
"length" : 30
}
}
>
学习mongo系列(十二)修改器($inc/$set/$unset/$push/$pop/upsert)
标签:
原文地址:http://www.cnblogs.com/mxh1099/p/5314800.html