【问题标题】:How to speed up query mongdb with mongoose in nodejs如何在节点 js 中使用 mongoose 加快查询 mongodb
【发布时间】:2019-04-04 16:24:27
【问题描述】:

我是 MongoDB 和 Node.js 的新手。

我编写了一个示例应用程序来测量使用 Mongoose 对 MongoDB 的获取请求的速度。

我有一个包含大约 200000 条记录的集合。 在我的代码中,我想通过查询获取前 100000 行:

var query = db.myCollection.find().limit(100000);
query.exec(function(err, data){
      // ....
});

大约花了99s,我认为速度太慢了。 有人对如何加快查询有任何想法吗?

非常感谢!

【问题讨论】:

  • 尝试为您的集合创建索引,因为没有索引,MongoDB 必须执行集合扫描,即扫描集合中的每个文档,以选择与查询语句匹配的那些文档,这会增加响应时间
  • 我认为 id 是 mongoDB 中的默认索引。
  • 是的,ObjectId 默认使用 mongo 进行索引
  • @julienBourdic:那么您有什么方法可以提高查询速度吗?

标签: javascript node.js mongoose mongodb-query


【解决方案1】:

使用 mongodb,您可以索引一些键以提高查询时的性能。但在这种情况下,这是行不通的。

您的 99 可能是由于您的 PC 无法一次性处理这种繁重的数据负载(这完全可以理解)。

这绝对与 mongodb 无关,而是与您的测试机内存有关。

但你也许可以通过管道来改进它:

// use our lame formatter
var format = new ArrayFormatter;

// first pipe the querystream to the formatter
myCollection.find().stream().pipe(format);

// then pipe the formatter to the response
// (node 0.4x style pipe non-chaining)
format.pipe(res);

// In node 0.6 we can P.find().stream().pipe(format).pipe(res);

this gist

【讨论】:

  • 感谢您的帮助。很难理解并适用于我的测试。
  • 我读了要点,真的不明白数据从数据库返回到哪里?
  • 将管道视为流。在本例中,这会从您的数据库生成连续的数据流到res。我建议您使用 nodejs 了解streams。这是最重要的 nodejs 原则之一。 This is the implementation on mongoose of the pipe
  • 我只是尝试这样做: var start = new Date(); var stream = db.Access.find().limit(100000).stream(); stream.on('data', function (doc){ // }).on('error', function (err) { // 处理错误 }).on('close', function () { // 的流已关闭 console.log(new Date().getTime() - start.getTime()); });但仍然花了大约 1 分 30 秒
  • 所以你赢了 9 秒。这对于一台计算机来说是相当大的 9 秒。通过除法,您每秒可以获得超过 1100 个结果。这也太棒了。
猜你喜欢
  • 2018-06-15
  • 2013-11-17
  • 2020-02-08
  • 2019-12-05
  • 2021-12-17
  • 1970-01-01
  • 2015-07-22
  • 2016-09-21
  • 2015-04-19
相关资源
最近更新 更多