javascript - 将过滤后的文档从 Mongo 集合传输到另一个集合的最佳方法(在 Nodejs 中)

标签 javascript node.js mongodb

我需要过滤一个大的 MongoDB 集合(今天,3500000 个文档,明天,更多......),并将其一些内容传输到一个空集合。这是我的 ES6 幼稚方法:

await col_target.drop();
const cursor = await col_source.find();

while (await cursor.hasNext()) {
  const doc = await cursor.next();
  
  // the filter is and array of regular expressions
  if (!regex.map(_ => new RegExp(_, 'imu').test(doc.rawJson.text)).reduce((a, b) => a || b)) continue;
  
  await col_target.insertOne(prepareTweet(doc));
}

await db.close();

我感觉这不是最佳的,因为查找和插入操作应该并行化。但我真的不知道该怎么做。有人可以向我提供有关如何改进代码的建议吗?

最佳答案

您应该在单个查询中执行此操作,这样会更快

db.col_source.aggregate([
    {$match: {rawJson: /someRegex/gi }},
    {$out: "col_target"}
])

当然,别忘了创建一个text indexrawJson 字段

关于javascript - 将过滤后的文档从 Mongo 集合传输到另一个集合的最佳方法(在 Nodejs 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42996687/

相关文章:

javascript - 当我使用 Ajax 刷新部分页面时,JS、jQuery 不起作用

javascript - 如何修复 'ERROR TypeError: data.slice is not a function'?

javascript - 为什么我使用 Next.js (React) 构建的 Shopify 应用加载速度如此缓慢?

node.js - 对 mongoose mapReduce 进行分页,用于排名算法

node.js - Mongoose 中的 Model.findOne() 和 Model.findById() 有什么区别?

node.js - mongoose 的错误不是 MongoError 的实例?

javascript - 当使用clearInterval清除并使用setInterval重置时,setInterval不会重新启动

javascript - 按下提交按钮后如何向 app.js 发送 POST 请求以显示 View 并渲染值?

javascript - nodejs/javascript中的递归原型(prototype)继承

javascript - WebSockets 与 Node.js 和 socket.io