Mongodb 更新数组 $push 操作符和去重复更新数组 $addToSet 操作符使用

一、$push

  1. $push 操作符添加指定的值到数组中,不去重
  2. 例如:添加一个值到数组中:
db.students.update(
   { _id: 1 },
   { $push: { scores: 89 } }
)
  1. 添加多个值到数组中
db.students.update(
   { name: "joe" },
   { $push: { scores: { $each: [ 90, 92, 89 ] } } }
)

结果:scores:[89,90,92,89]

二、$addToSet

  1. mongodb 新版本(2.3)中有一个 $addToSet 这个方法向数组中增加值,自动去重复
  2. 例如:添加一个值到数组中
db.students.update(
	{'name':'joe'}, 
	{'$addToSet':{scores:89}}
	);
  1. 添加多个值到数组中
db.students.update(
	{'name':'joe'}, 
	{'$addToSet':{scores:{'$each':[90, 92, 89]}}
	);

结果:scores:[89,90,92]

posted @ 2018-11-14 09:59  王图思睿  阅读(260)  评论(0)    收藏  举报