MongoDB批量插入忽略重复

时间:2016-08-20 13:24:30

标签: node.js mongodb

我已经用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(...),但这不起作用。

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

另一种方法是使用 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()
        }
    } 
})
相关问题