限制mongodb插入的数量

时间:2014-12-28 01:47:35

标签: node.js mongodb nosql

是否可以使用mongodb客户端在node.js中通过批量插入插入的文档数量设置固定限制?

我通过批量插入将一些文档插入到fieldA上具有唯一索引的集合中。由于fieldA不是唯一的,因此有些插入会失败,因此我无法预先知道将插入多少插入,但我想限制nInserted以便这些插入的总数文件永远不会超过5000。

我所能想到的就是运行完整插入,如果nInserted总计超过5000,我删除n最后插入的文档,使得总数为5000,但这看起来有点傻

订购的批量插入几乎是正确的,但我不希望它在第一次索引冲突时停止,但如果仍有空间(即总<5000),则继续前进。

以下是我尝试实现的一个例子:

db.myCol.count({foo: val}, function(err, count) {
    var remaining = 5000 - count;
    if (remaining > 0) {
        var bulk = db.myCol.initializeUnorderedBulkOp();
        toInsert.forEach(function(item) {
            bulk.insert(item);
        });

        // make sure no more than remaining is inserted
        bulk.execute(function(err, result) {
            // currently, I would just insert all and
            // then remove the overflow with another db action
            // if nInserted + count > 5000
        });
    }
});

1 个答案:

答案 0 :(得分:0)

目前,一旦达到成功插入的限制,就无法告诉Bulk API停止插入任何记录。 在客户端进行此操作的一种方法,

  • Bulk API最多提供n(本例中为5000)文档 时间
  • 如果在插入过程中发生任何错误,请批量插入 剩余。
  • 递归地做。
  • 您可以进一步添加逻辑以仅处理剩余的数量 记录remaining < max

修改后的代码:

var toInsert = [..];  // documents to be inserted.

var max = 5000;  // max records for Bulk insert.

function execBulk(start,end){
    db.myCol.count({foo: 'bar'}, function(err, count) {
    var remaining = total - count;
    if (remaining > 0 && toInsert.length > start) {
        var bulk = db.myCol.initializeUnorderedBulkOp();
        toInsert.slice(start,end).forEach(function(item) {
            bulk.insert(item);
        });
        // insert the records
        bulk.execute(function(err, result) {
            if(err){
              console.log(err);
              // insert next set of at most 5000 records.
              execBulk(end,end+max-1)
            }
            else
            {
                console.log(results);
            }
        });
    }
});
}

调用函数:

execBulk(0,max);