插入logging不失败重复

我使用最新的node.js原生驱动程序(2.0)批量插入大量文档。

我的集合在URL字段中有一个索引,我必须从插入的数千行中获取重复项。 有没有办法让MongoDB遇到重复时不会崩溃?

现在我正在批量logging1000,并使用insertMany。 我尝试了各种各样的东西,包括添加{continueOnError = true}。 我试图一个接一个地插入我的logging,但是速度太慢了,我有成千上万的工人在队列中,并且不能真正负担延迟。

集合定义:

self.prods = db.collection('products'); self.prods.ensureIndex({url:1},{unique:true}, function() {}); 

插 :

 MongoProcessor.prototype._batchInsert= function(coll,items){ var self = this; if(items.length>0){ var batch = []; var l = items.length; for (var i = 0; i < 999; i++) { if(i<l){ batch.push(items.shift()); } if(i===998){ coll.insertMany(batch, {continueOnError: true},function(err,res){ if(err) console.log(err); if(res) console.log('Inserted products: '+res.insertedCount+' / '+batch.length); self._batchInsert(coll,items); }); } } }else{ self._terminate(); } }; 

我正在考虑在插入之前删除索引,然后使用dropDups进行重新索引,但是看起来有点不好意思,我的工作人员是聚集在一起的,而我不知道如果他们尝试在另一个进程重新索引时插入logging会发生什么情况。谁有更好的主意?

编辑:

我忘了提到一件事。 我插入的项目有一个“已处理”字段,设置为“假”。 然而,已经在数据库中的项目可能已经被处理,所以该字段可以是“真”。 因此,我不能upsert …或者我可以select一个字段是由upsert未触及?

2.6 Bulk API是你正在寻找的,这将需要MongoDB 2.6+ *和节点驱动程序1.4+。

有两种types的批量操作:

  1. 有序批量操作 。 这些操作按顺序执行所有操作,并在第一次写入错误时出错。
  2. 无序的批量操作 。 这些操作并行地执行所有操作并聚合所有的错误。 无序批量操作不保证执行顺序。

所以在你的情况下无序是你想要的。 上一个链接提供了一个例子:

 MongoClient.connect("mongodb://localhost:27017/test", function(err, db) { // Get the collection var col = db.collection('batch_write_ordered_ops'); // Initialize the Ordered Batch var batch = col.initializeUnorderedBulkOp(); // Add some operations to be executed in order batch.insert({a:1}); batch.find({a:1}).updateOne({$set: {b:1}}); batch.find({a:2}).upsert().updateOne({$set: {b:2}}); batch.insert({a:3}); batch.find({a:3}).remove({a:3}); // Execute the operations batch.execute(function(err, result) { console.dir(err); console.dir(result); db.close(); }); }); 

*文档确实声明:“ 对于比2.6更老的服务器,API将下载转换操作,但不可能下转换100%,因此可能会出现轻微的边缘情况,无法正确报告正确的数字。