MongoDB update修改器: $inc $set $unset $push $pull $pop
针对Fields的$修改器
$set:
{ $set: { key: value } }
$set:{"gender":"男"} 解释: $set 是update时的关键字,表示我要设置gender属性的值为"男"
如果该条Documents没有gender属性,他就会自动创建一个gender属性并且赋值为"男"
$set是修改器之一 :设置将某key设置为某值
例子:
1.把 "age" 为 13 的数据 "gender" 赋值为 "男",没有这个字段会自动创建一个gender字段,并且赋值为"男"
> db.user.updateOne({age:13},{$set:{"gender":"男"}}) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } > > > db.user.find({age:13}) { "_id" : ObjectId("5ca7a4c4219efd687462f968"), "id" : 4, "name" : "xiaogang", "age" : 13, "hobby" : [ "羽毛球", "篮球", "足球" ], "gender" : "男" }
2.把"age"为13的数据 “gender”赋值为"女"
> db.user.updateOne({age:13},{$set:{"gender":"女"}}) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } > > db.user.find({age:13}) { "_id" : ObjectId("5ca7a4c4219efd687462f968"), "id" : 4, "name" : "xiaogang", "age" : 13, "hobby" : [ "羽毛球", "篮球", "足球" ], "gender" : "女" }
$unset:
{ $unset: { key: 1} }
用来删除当前Key(field)的
例子:
删除age=13的数据的gender这个fields
> db.user.updateOne({age:13},{$unset:{"gender":1}} ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } > > db.user.find({age:13}) { "_id" : ObjectId("5ca7a4c4219efd687462f968"), "id" : 4, "name" : "xiaogang", "age" : 13, "hobby" : [ "羽毛球", "篮球", "足球" ] }
成功了! {$unset:{"gender" : 1}} 就是删除 "gender" 这个 fields 相当于 关系型数据库中删除了 字段
$inc:
{ $inc: { key: value } }
类似于Python中的 变量 += 1 , 将查询到的结果 加上某一个值 然后保存
在原有值的基础上增加多少,
对文档的某个值为数字型(只能为满足要求的数字)的键进行增减的操作。
{$inc:{age:1} } 在年龄原有基础加一岁
> db.user.find() { "_id" : ObjectId("5ca7a4b0219efd687462f965"), "id" : 1, "name" : "jack", "age" : 73 } { "_id" : ObjectId("5ca7a4b7219efd687462f966"), "id" : 2, "name" : "mike", "age" : 84, "gender" : "男" } { "_id" : ObjectId("5ca7a4c4219efd687462f967"), "id" : 3, "name" : "peter", "age" : 21 } { "_id" : ObjectId("5ca7a4c4219efd687462f968"), "id" : 4, "name" : "xiaogang", "age" : 13, "hobby" : [ "羽毛球", "篮球", "足球" ] } { "_id" : ObjectId("5ca7a4c4219efd687462f969"), "id" : 5, "name" : "ben", "age" : 24 } { "_id" : ObjectId("5ca7a505219efd687462f96a"), "id" : 6, "name" : "Mary", "age" : 84, "gender" : "男" }
把age=13的数据age增加一岁
> db.user.updateOne({age:13},{$inc:{age:1}} ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } > db.user.find({age:13}) > db.user.find({age:14}) { "_id" : ObjectId("5ca7a4c4219efd687462f968"), "id" : 4, "name" : "xiaogang", "age" : 14, "hobby" : [ "羽毛球", "篮球", "足球" ] }
成功了 , {$inc:{"age":1}}的意思是,"age"的原有数值上面 +1,
那我们再来实验一次,把14改为34,这怎么操作呢,其实可以理解为在 14 上加一个 20
> db.user.updateOne({age:14},{$inc:{age:20}} ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } > db.user.find({age:34}) { "_id" : ObjectId("5ca7a4c4219efd687462f968"), "id" : 4, "name" : "xiaogang", "age" : 34, "hobby" : [ "羽毛球", "篮球", "足球" ] }