mongodb $push 重复怎么办

355次阅读
没有评论

mongodb

一、$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]

python学习网,大量的免费MongoDB入门教程,欢迎在线学习!

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:MongoDB2022-12-06发表,共计572字。
新手QQ群:570568346,欢迎进群讨论 Python51学习