开发者社区> 问答> 正文

mongodb $push 重复怎么办

mongodb $push 重复怎么办

展开
收起
社区秘书 2019-12-10 15:59:35 542 0
1 条回答
写回答
取消 提交回答
  • 
    $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]
    
    2019-12-10 15:59:48
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
MongoDB多数据中心的方案选型之路 立即下载
阿里云MongoDB云服务构建 立即下载
饿了么高级架构师陈东明:MongoDB是如何逐步提高可靠性的 立即下载

相关实验场景

更多