【发布时间】:2017-07-03 06:48:01
【问题描述】:
有没有办法使用node.js 客户端在mongodb 中通过批量插入来设置可以插入的文档数量的固定限制?
我通过批量插入将多个文档插入到集合中,该集合在fieldA 上具有唯一索引。由于fieldA 不唯一,一些插入会失败,所以我不知道会预先插入多少,但我想限制nInserted,这样这些文档的总数就不会超过5000。
我能想到的就是运行完整的插入,如果 nInserted 使总数超过 5000,我将删除最后插入的 n 文档,使总数为 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
});
}
});
【问题讨论】:
-
那么,一旦批量操作完成,您希望集合中有 5000 条记录吗?您可以发布您尝试过的实现吗?
-
@BatScream 我想确保在运行批量插入后不超过 5000 个特定类型的文档 > 5000。我已经更新了这个问题来举个例子。