Mongodb中更新的学习小结

今天继续很久没学习的mongodb的简单学习,今天来看的是更新。先来看简单的用法: 

use updatetest 
>switched to db updatetest 

首先插入一下: 
db.things.insert( { name : "test1"} ) 

db.things.find({name : "test1"}) 
会找到: 
  { "_id" : ObjectId("50f1778ea5ec290b7773303b"), "name" : "test1" } 

  更新的格式为: 
  db.collection.update( criteria, objNew, upsert, multi ) 
参数: 
criteria - 查询需要更新的项; 
objNew - 更新的对象或者 $ operators (例如 $inc) 这样的操作因子 
upsert - 是否是 "upsert"; 也就是说如果记录不存在是否插入新的记录 
multi - 是否所有满足criteria的在整个文档都更新 
注意:在缺省情况下,update()只会更新第一个满足条件的项。如果需要修改所以的满足条件的 
项的话,需要使用multi这个标志位。 

  db.things.update({name: "test1"}, {name: "test2"}) 
再find一下 
  db.things.find({name : "test2"}) 
会发现有test2了; 
   再来: 
db.things.update({name : "hello"}, {name: "hello,abc"}, true); 
  注意参数true这里的用法,结果为,因为hello没有,所以只会插入 
hello,abc了。 
  也可以写成: 
  db.things.update({name : "hello"}, {name: "hello,abc"}, { upsert: true }); 
注意: 
1、update方法只更新一条记录 
默认情况下update只更新符合查询条件的第一条找到的记录。如果想更新所有符合条件的记录,需要手动添加 multi 这个参数。 

2、update方法的更新参数 
像下面这个语句 
updatetest.update( { _id: X }, {name: "Joe", age: 20 }); 
会把符合条件的原纪录按照{name: "Joe", age: 20 }完整替换,而不是简单的将name设为"Joe",age设为20. 
如果只想更改这2个值,而不是替换完整对象,应该写 
updatetest.update( { _id: X },{$set: {name: "Joe", age: 20 }}); 
   
   $inc的用法,比如统计经常要用到了,如: 
  db.things.update({BlogPost: "How To Do Upserts"}, {$inc: {Hits: 1}}, { upsert: true }); 
   
db.things.find({BlogPost : "How To Do Upserts"}) 
>{ "_id" : ObjectId("50f17b4541c33bd2459aafed"), "BlogPost" : "How To Do Upserts", "Hits" : 1 } 
再多运行两次: 

  db.things.update({BlogPost: "How To Do Upserts"}, {$inc: {Hits: 1}}, { upsert: true }); 
db.things.update({BlogPost: "How To Do Upserts"}, {$inc: {Hits: 1}}, { upsert: true }); 
>db.things.find({BlogPost : "How To Do Upserts"}) 

>{ "_id" : ObjectId("50f17b4541c33bd2459aafed"), "BlogPost" : "How To Do Upserts", "Hits" : 3 } 

可以看到,hits变为3了。 
    
multi的用法: 
   比如: 
db.Indexing.insert( { name : "Denis", age : 10 } ) 
db.Indexing.insert( { name : "Denis", age : 20 } ) 
db.Indexing.insert( { name : "Denis", age : 30 } ) 

要将所有的denies的age都更新,必须加行multi: 
db.Indexing.update({name: "Denis"}, {$set: {age: 42}},{ multi: true })

原文地址:https://www.cnblogs.com/ctp0925/p/3429745.html