mongodb的update

来源:互联网 发布:进销存软件哪款好 编辑:程序博客网 时间:2024/05/22 13:31

mongodb的update篇


mongodb的update还是可以很强大的

db.collection.update( criteria, objNew, upsert, multi )

  • criteria - query which selects the record to update;
  • objNew - updated object or $ operators (e.g., $inc) which manipulate the object
  • upsert - if this should be an "upsert" operation; that is, if the record(s) do not exist, insert one. Upsert only inserts a single document.            boolean
  • multi - indicates if all documents matching criteria should be updated rather than just one. Can be useful with the $ operators below.
例子
db.people.update( { name:"Joe" }, {  $set : { x : 1 },$inc: { n : 1 } ,$unset : { field : 1}} );
一些update操作符

  • $inc
  • $set
  • $unset
  • $push
  • $pushAll
  • $addToSet
  • $pop
  • $pull
  • $pullAll
  • $rename
  • $bit
{ $push : { field : value } }
向field 字段的array里面 添加 一个value,如果filed字段不是array则报错。

{ $pushAll : { field : value_array } }
和push不同的是添加的 是 array,是多个值。

{ $addToSet : { field : value } }
和push不同的就是 添加 如果是filed的array里面已经存在的value,就不添加

{ $pop : { field : 1  } }  删除array里面最后一个
{ $pop : { field : -1  } }  删除第一个
{ $pull : { field : {field2: value} } } removes array elements with field2 matching value 
比如 { $pull : { groups:{groupName : "groupName"} } } 其中 groupName是groups集合中元素 group的 属性
{ $pull : { field : {$gt: 3} } } removes array elements greater than 3
{ $pull : { field : {<match-criteria>} } } removes array elements meeting match criteria
{ $pullAll : { field : value_array } }
value_array里面主要是符合的都删除

{ $rename : { old_field_name : new_field_name } }

{$bit : { field : {and : 5}}}{$bit : {field : {or : 43}}}{$bit : {field : {and : 5, or : 2}}}

Does a bitwise update of field. Can only be used with integers.

The $ positional operator

t.update( {'comments.by':'joe'}, {$inc:{'comments.$.votes':1}}, false, true )
The $ operator (by itself) means "position of the matched array item in the query"















原创粉丝点击