4). $inc
用法:{$inc:{field:value}} 意思是对一个数字字段field增加value:
> db.mytest.find({_id:1})
{ "_id" : 1, "name" : "test1", "count" : 1 }
> db.mytest.update({_id:1},{$inc:{count:1}})
> db.mytest.find({_id:1})
{ "_id" : 1, "name" : "test1", "count" : 2 } //count字段加1
value的值也可以为负,就相当于减一个值:
> db.mytest.update({_id:1},{$inc:{count:-2}})
> db.mytest.find({_id:1})
{ "_id" : 1, "name" : "test1", "count" : 0 } //值从2减到0
5). $set命令
用法:{$set:{field:value}}
相当于在关系型数据库中sql的set field=value,全部数据类型都支持$set操作
> db.mytest.update({_id:1},{$set:{count:111}})
> db.mytest.find({_id:1})
{ "_id" : 1, "name" : "test1", "count" : 111 } //修改数值型
> db.mytest.update({_id:1},{$set:{name:"MongoDB"}})
> db.mytest.find({_id:1})
{ "_id" : 1, "count" : 111, "name" : "MongoDB" } //修改字符型
6). $unset
用法:{$unset:{field:1}}
> db.mytest.find({_id:1})
{ "_id" : 1, "count" : 111, "name" : "MongoDB" }
> db.mytest.update({_id:1},{$unset:{name:1}})
> db.mytest.find({_id:1})
{ "_id" : 1, "count" : 111 } //删除了字段name
7). $push
用法:{$push:{field:value}}
把value追加到field中取,field一定是数据类型才行,如果field不存在,会新增一个数组类型加进去:
> db.mytest.update({_id:15},{$set:{array:["aaa","bbb"]}})
> db.mytest.find({_id:15})
{ "_id" : 15, "array" : [ "aaa", "bbb" ], "count" : 15, "name" : "ok123" }
使用push追加数据:
> db.mytest.update({_id:15},{$push:{array:"ccc"}})
> db.mytest.find({_id:15})
{ "_id" : 15, "array" : [ "aaa", "bbb", "ccc" ], "count" : 15, "name" : "ok123" }
push一次只能追加一个值,如果需要追加多个值,则需要使用$pushAll:
> db.mytest.update({_id:15},{$pushAll:{array:["ddd","eee","fff"]}})
> db.mytest.find({_id:15})
{ "_id" : 15, "array" : [ "aaa", "bbb", "ccc", "ddd", "eee", "fff" ], "count" : 15, "name" : "ok123" }
