mongodb update fields 操作符
mongodb 2.4操作符:
$setOnInsert, $set, $unset, $inc, $rename,
rs0:PRIMARY> db.my.update({name : "xiaobao"}, {$setOnInsert : {age : 10}}, {upsert : true})
rs0:PRIMARY> db.my.update({name : "caoqing"}, {age : 10}, {upsert : true})
rs0:PRIMARY> db.my.find()
{ "_id" : ObjectId("53a121b74aafa8f47ca82b6c"), "age" : 10, "name" : "xiaobao" }
{ "_id" : ObjectId("53a121c34aafa8f47ca82b6d"), "age" : 10 }
rs0:PRIMARY> db.my.update({name : "xiaobao"}, {$set : {father : "caoqing"}})
rs0:PRIMARY> db.my.find()
{ "_id" : ObjectId("53a121c34aafa8f47ca82b6d"), "age" : 10 }
{ "_id" : ObjectId("53a121b74aafa8f47ca82b6c"), "age" : 10, "father" : "caoqing", "name" : "xiaobao" }
rs0:PRIMARY> db.my.update({name : "xiaobao"}, {$unset : {father : ""}})
rs0:PRIMARY> db.my.find()
{ "_id" : ObjectId("53a121c34aafa8f47ca82b6d"), "age" : 10 }
{ "_id" : ObjectId("53a121b74aafa8f47ca82b6c"), "age" : 10, "name" : "xiaobao" }
rs0:PRIMARY> db.my.update({name : "xiaobao"}, {$inc : {age : 100}})
rs0:PRIMARY> db.my.find()
{ "_id" : ObjectId("53a121c34aafa8f47ca82b6d"), "age" : 10 }
{ "_id" : ObjectId("53a121b74aafa8f47ca82b6c"), "age" : 110, "name" : "xiaobao" }
rs0:PRIMARY> db.my.update({name : "xiaobao"}, {$rename : {"name" : "son"}})
rs0:PRIMARY> db.my.find()
{ "_id" : ObjectId("53a121c34aafa8f47ca82b6d"), "age" : 10 }
{ "_id" : ObjectId("53a121b74aafa8f47ca82b6c"), "age" : 110, "son" : "xiaobao" }
mongodb 2.6新操作符:
$mul, $min, $max, $currentDate
rs0:PRIMARY> db.my.update({son : "xiaobao"}, {$min : {age : 10}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
rs0:PRIMARY> db.my.find()
{ "_id" : ObjectId("53a121c34aafa8f47ca82b6d"), "age" : 10 }
{ "_id" : ObjectId("53a121b74aafa8f47ca82b6c"), "age" : 10, "son" : "xiaobao" }
rs0:PRIMARY> db.my.update({son : "xiaobao"}, {$min : {age : 20}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
rs0:PRIMARY> db.my.find()
{ "_id" : ObjectId("53a1219d4aafa8f47ca82b6b"), "age" : 10 }
{ "_id" : ObjectId("53a121b74aafa8f47ca82b6c"), "age" : 10, "son" : "xiaobao"
rs0:PRIMARY> db.my.update({son : "xiaobao"}, {$mul : {age : 0.1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
rs0:PRIMARY> db.my.find()
{ "_id" : ObjectId("53a121b74aafa8f47ca82b6c"), "age" : 10, "son" : "xiaobao", "birth" : ISODate("2014-06-18T06:00:25.628Z") }
{ "_id" : ObjectId("53a121c34aafa8f47ca82b6d"), "age" : 10 }
转载于:https://my.oschina.net/u/1449160/blog/280979