【问题标题】:How to avoid inserting duplicate values in the collection using db.insertMany() in MongoDB?如何避免在 MongoDB 中使用 db.insertMany() 在集合中插入重复值?
【发布时间】:2019-03-12 19:44:48
【问题描述】:

查询:

db.getCollection('parents').insertMany(
    [{
        'name': 'Mark',
        'children': 'No Childs'
    },{
        'name': 'Carl',
        'children': '2'
    }], {
      'ordered': true,
    }
)

我使用猫鼬作为 ORM

是否有人可以建议我们是否有任何选项,例如 unique: true ? 我希望检查内容而不是 _id,因为它永远不会重复

注意:我试过 findOneAndUpdate 使用 upsert: true,但在这里我必须同时插入多个文档

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    在定义模型架构时,您可以指定哪个字段是唯一的,例如:

    var userSchema = new mongoose.Schema(
    { 
      FieldName:{ 
                 type: String, 
                 unique:true 
                }
    })
    var UserModel = mongoose.Model('User',userSchema);
    

    如果你只想添加索引有

    schema.index({FieldName1: 1, FieldName2: 1}, {unique: true});
    

    Or more details can be found here

    【讨论】:

      【解决方案2】:

      根据文档,如果您在某个字段上有一个唯一索引(在您的情况下为 name)并且您尝试使用 insertMany 插入多个文档,那么在发生错误时您将收到异常:

      为作为唯一键的一部分的任何键插入重复值 index,比如_id,会抛出异常。

      但是,如果您设置 'ordered': false,insertMany 的执行将不会停止,并且您会插入那些unique 索引冲突的文档:

      ordered 为 false 时,插入操作将继续 剩下的文件。

      所以在name 字段上设置一个唯一索引,当你这样做时insertMany only those records which violate that index would be skipped

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-31
        • 1970-01-01
        • 2014-07-30
        • 2021-03-06
        • 1970-01-01
        相关资源
        最近更新 更多