【问题标题】:MongoDB Bulk Insert Ignore DuplicateMongoDB批量插入忽略重复
【发布时间】:2018-03-07 03:00:42
【问题描述】:

我在 Google 上四处搜索,找不到任何关于如何在使用批量插入时忽略重复错误的可靠信息。

这是我目前使用的代码:

MongoClient.connect(mongoURL, function(err, db) {
      if(err) console.err(err)
      let col = db.collection('user_ids')
      let batch = col.initializeUnorderedBulkOp()

      ids.forEach(function(id) {
        batch.insert({ userid: id, used: false, group: argv.groupID })
      })

      batch.execute(function(err, result) {
        if(err) {
          console.error(new Error(err))
          db.close()
        }

        // Do some work

        db.close()
      })
    })

有可能吗?我尝试将{continueOnError: true, safe: true} 添加到bulk.insert(...),但没有成功。

有什么想法吗?

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    另一种方法是使用 bulk.find().upsert().replaceOne() 代替:

    MongoClient.connect(mongoURL, function(err, db) {
        if(err) console.err(err)
        let col = db.collection('user_ids')
        let batch = col.initializeUnorderedBulkOp()
    
        ids.forEach(function(id) {        
            batch.find({ userid: id }).upsert().replaceOne({ 
                userid: id, 
                used: false,  
                group: argv.groupID 
            });
        });
    
        batch.execute(function(err, result) {
            if(err) {
                console.error(new Error(err))
                db.close()
            }
    
            // Do some work
    
            db.close()
        });
    });
    

    如上,如果一个文档与查询{ userid: id }匹配,它将被新文档替换,否则将被创建,因此不会抛出重复键错误。


    对于 MongoDB 服务器版本 3.2+,使用 bulkWrite 作为:

    MongoClient.connect(mongoURL, function(err, db) {
    
        if(err) console.err(err)
    
        let col = db.collection('user_ids')
        let ops = []
        let counter = 0
    
        ids.forEach(function(id) {
            ops.push({
                "replaceOne": {
                    "filter": { "userid": id },
                    "replacement": { 
                        userid: id, 
                        used: false,  
                        group: argv.groupID 
                    },
                    "upsert": true
                }
            })
    
            counter++
    
            if (counter % 500 === 0) {
                col.bulkWrite(ops, function(err, r) {
                    // do something with result
                    db.close()
                })
                ops = []
            }
        })
    
        if (counter % 500 !== 0) {
            col.bulkWrite(ops, function(err, r) {
                // do something with result
                db.close()
            }
        } 
    })
    

    【讨论】:

      猜你喜欢
      • 2016-07-29
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 2012-08-07
      • 2019-09-20
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      相关资源
      最近更新 更多