一、$push
- $push 操作符添加指定的值到数组中,不去重
- 例如:添加一个值到数组中:
db.students.update(
{ _id: 1 },
{ $push: { scores: 89 } }
)
- 添加多个值到数组中
db.students.update(
{ name: "joe" },
{ $push: { scores: { $each: [ 90, 92, 89 ] } } }
)
结果:scores:[89,90,92,89]
二、$addToSet
- mongodb 新版本(2.3)中有一个 $addToSet 这个方法向数组中增加值,自动去重复
- 例如:添加一个值到数组中
db.students.update(
{'name':'joe'},
{'$addToSet':{scores:89}}
);
- 添加多个值到数组中
db.students.update(
{'name':'joe'},
{'$addToSet':{scores:{'$each':[90, 92, 89]}}
);
结果:scores:[89,90,92]