javascript - Mongodb 并行运行数千个查询

标签 javascript node.js mongodb concurrency

我们有一个 PHP 应用程序,在 mongo 集合中运行 30k 个唯一查询时表现良好。

foreach ($request->numbers as $number) {
    $query = [
        'cn' => $ddd,
        'prefix_init' => array('$lte' => (int) $mobile),
        'prefix_final' => array('$gte' => (int) $mobile)
    ];

    $result = $cadup_full->findOne($query);
    $results[] = $result;
}

我们在 NodeJS 中转换了该应用程序,并开始出现性能问题,因为在 PHP 中查询是以同步方式触发的,而 NodeJS 循环使所有 30k 程序同时运行,从而导致性能下降。

如何利用仍使用 Nodejs 运行这些查询的优势?

最佳答案

正如 JohnnyHK 提到的,您可以使用 async ,具体来说mapLimit .

我不懂 PHP,所以这里是对它在 Node 中的等效语法的伪/粗略猜测。

// max number of requests running at once
let concurrencyLimit = 10;

async.mapLimit(numbers, concurrencyLimit, function(number, numberCallback) {

    let query = {
        "cn": ddd,
        "prefix_init": {
            $lte: number
        },
        "prefix_final": {
            $gte: number
        }
    }

    // where numberCallback is function(error, document);
    myCollection.findOne(query, numberCallback);

}, function(error, results) {

    // here is your results array;
    console.log(results);
});

关于javascript - Mongodb 并行运行数千个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37255633/

相关文章:

node.js - Mongoose 使用不同的外键加入两个不同的集合

node.js - 未解析 Google Cloud Run 中的结构化日志(使用 Winston 进行日志记录)

node.js - 如何在 Mongoose 中创建迁移?

javascript - 如何将分离的 li 元素添加到 ul 列表

javascript - 在扩展 native 类的 ScalaJS 类中调用重载的 super 构造函数

javascript - 如何在指定符号前添加符号?

node.js - 使用nodejs更新mongoDB中的表单值时出错

javascript - 禁用除 DIV 元素之外的所有元素

javascript - 解析一个以变量为名称的 json 对象

mongodb 更改 $group 输出格式