【问题标题】:How to quickly retrieve large array from MongoDB如何从 MongoDB 中快速检索大数组
【发布时间】:2019-03-26 01:47:44
【问题描述】:

我在 MongoDB 集合中有一个 500kb 的文档,看起来像这样,“Content”数组有 5000 个条目:

{
  "BookID": "120",
  "Content": ["The day was pretty good", .42], 
             ["The day was great!", .83],
             .....
}

使用 Express 从 Node 运行查询耗时过长:500 - 5000ms

app.get('/sentences', function (req, res) {
  start = Date.now();
  db.collection('Sentences').find({ "BookID": "120"}).toArray(function (findErr, result) {
      if (findErr) throw findErr;
      console.log(Date.now() - start);
      res.send(result[0]);  
  });
}

有没有合适的方法来存储或查询这样的数据并获得快速的查询时间,或者我应该使用 MongoDB 以外的东西吗?最终,我想存储数千本这样的书籍,而不需要复杂的查询。

【问题讨论】:

  • BookID 字段是数据库中的数字还是字符串?
  • 当我从 Python 插入时,BookID 字段是一个字符串。在数据库中我猜它不是一个字符串。

标签: node.js database mongodb express


【解决方案1】:

使用hint 提高查询性能。

app.get('/sentences/:id', function (req, res) {
 var bookID=req.params.id

 start = Date.now();
      db.collection('Sentences')
     .find()
     .hint("BookID_"+bookID)
     .toArray(function (findErr, result) {
       if (findErr) throw findErr;
        console.log(Date.now() - start);
        res.send(result[0]);  
  });
}

【讨论】:

  • 这使代码更简洁,但对缩短查询时间没有任何帮助,因为集合中只有一个文档。
【解决方案2】:

我假设您已经索引了该集合(如果没有,请 去做。它会使其更快),但查询仍然很慢。

由于这是获取数据的直接查询(甚至不是复杂的搜索),因此很难使用传统方法使其更快。但是根据您的用例,您可以让它更快,

比如用Redis缓存结果。

【讨论】:

    【解决方案3】:

    如果您不打算对输出文档执行任何添加、更新、删除命令,请在查询中使用 lean()。使用精益将在 javascript 中提供输出,并且任何 mongoose 命令都不适用于结果文档。 http://www.tothenew.com/blog/high-performance-find-query-using-lean-in-mongoose-2/

    db.collection('Sentences').find({ "BookID": "120"}).lean().toArray(function (findErr, result) {
      if (findErr) throw findErr;
      console.log(Date.now() - start);
      res.send(result[0]);  
    });
    

    【讨论】:

    • lean() 是 Mongoose 的东西,但 OP 没有使用它。
    【解决方案4】:

    我最终将数据作为 JSON 文件存储在 S3 中。更快更便宜

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 2017-10-17
      • 2019-10-04
      相关资源
      最近更新 更多