1.update

  1. db.user.update({name:"chengcheng"},{$set:{"name":"jiangwei"}})

如果不加$set,会将那条数据完全替换

  1. db.user.update({name:"jiangwei"},{name:"huan"}})

2.remove删除某条数据

  1. db.collectionName.remove(condition)
  1. db.user.remove({name:'li'})

2.1justOne:true只删除一条数据

  1. db.user.remove({name:"shanshan"},{justOne:true})

3.更新内嵌数组中某条数据

  1. //user
  2. //更新cartList中id等于1002这条数据,将num设置为2
  3. {
  4. _id: 4,
  5. cartList: [
  6. { id: 1001, num: 1, name: "手机" },
  7. { id: 1002, num: 1, name: "电脑" },
  8. { id: 1003, num: 1, name: "平板" }
  9. ]
  10. }
  1. db.user.update({_id:4,"cartList.id":1001},{$set:{"cartList.$.num":2}})

4.批量给每一条ducment新增字段 updateMany

_id ObjectId name
6036f806380b430ecc16b08a “lisi”
6036f865380b430ecc16b08b “wangwu”
  1. db.user.updateMany({like:{$exists:false}},{$set:{like:false}})
_id ObjectId name like
6036f806380b430ecc16b08a “lisi” false
6036f865380b430ecc16b08b “wangwu” false

5 单条记录新增/删除字段

5.1 删除

  1. db.user.update({name:"lisi"},{$unset:{like:false}})
  2. //删除like:false的这个字段

5.2添加

  1. db.user.update({name:"lisi"},{$set:{like:false}})

6 批量的删除某一个字段

  1. db.user.update({like:false},{$unset:{like:false}})