您的位置:首页 > 数据库 > Mongodb

MongoDB 修改器

2016-01-06 00:00 766 查看
摘要: MongoDB 修改器

$inc  修改增加的值

//demo:
//查看已有的一条数据
db.stone.find();
//查询结果:
{ "_id" : ObjectId("568b657d30b22da545433c22"), "name" : "stone", "age" : 118 }

//$inc 值能修改数值类型
db.stone.update({"name":"stone"},{"$inc":{"age":1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) //成功提示

//如果$inc 修改不是 整形或者浮点型 就会报错
//插入一条数据,age 设置为字符串类型(关于mongodb的数据类型,目前还没有接触,
//以后会专门拿出出时间学习一下数据类型)
db.stone.insert({"name":"stoneString","age":"18"})

//修改 age
db.stone.update({"name":"stoneString"},{"$inc":{"age":1}})
//报错如下

WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "Cannot apply $inc to a value of non-numeric type. {_
id: ObjectId('568cb1793c8dd16060b20a42')} has the field 'age' of non-numeric typ
e String"
}
})

//Cannot apply $inc to a value of non-numeric type.

$inc 修改器是 增加或者 减少相应的 数值。

$set 修改器是 指定一个键的值

//查询已有数据
db.stone.find();
{ "_id" : ObjectId("568b657d30b22da545433c22"), "name" : "stone", "age" : 119 }
{ "_id" : ObjectId("568cb1793c8dd16060b20a42"), "name" : "stoneString", "age" :"18" }

//设置 stoneString  age 为 77
db.stone.update({"name":"stoneString"},{"$set":{"age":77}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) //成功提示

//查看结果
db.stone.find();
{ "_id" : ObjectId("568b657d30b22da545433c22"), "name" : "stone", "age" : 119 }
{ "_id" : ObjectId("568cb1793c8dd16060b20a42"), "name" : "stoneString", "age" :77 }

//$set 可以修改数据类型  字符串 修改为 数值
db.stone.update({"name":"stoneString"},{"$set":{"age":77}})
{ "_id" : ObjectId("568b657d30b22da545433c22"), "name" : "stone", "age" : 119 }
{ "_id" : ObjectId("568cb1793c8dd16060b20a42"), "name" : "stoneString", "age" :77 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  MongoDB