简体   繁体   English

NodeJS 和 MongoDB 查询速度慢

[英]NodeJS and MongoDB Query Slow

so running into an issue where I am using NodeJS with Express for API calls.所以遇到了一个问题,我将 NodeJS 与 Express 一起用于 API 调用。 I am fetching all documents in a collection using我正在使用获取集合中的所有文档

    export async function main(req, res) {
    try {
        const tokens = await tokenModel.find({}).lean();
        res.json(tokens);
    } catch {(err) => {
        res.status(500).json({ message: err.message })
        console.log('err', err.message)
        }
    }
  console.log('Get Data')
}

Now this request works great and returns me the data I need.现在这个请求运行良好并返回我需要的数据。 The problem is I have over 10K documents, and on a PC takes about 10 seconds to return that data, and on a mobile phone it takes over 45 seconds.问题是我有超过 10K 个文档,在 PC 上大约需要 10 秒才能返回该数据,而在手机上则需要 45 秒以上。 I know network on phone matters, but is there any way I can increase this?我知道电话网络很重要,但有什么办法可以增加它吗? Nothing I have tried works.我没有尝试过。 I keep finding that lean is the option to use, and I am already using it with no success or improvements.我一直发现精益是可以使用的选项,而且我已经在使用它但没有成功或改进。

Well, it's slow because you are returning all 10k results.好吧,它很慢,因为您要返回所有 10k 个结果。

Do you actually need all 10k results?您真的需要所有 10k 个结果吗? If not, you should consider filtering only results that you actually need.如果不是,您应该考虑仅过滤您实际需要的结果。

If not, I suggest implementing pagination, where you would return results in batches (50 per page for example).如果没有,我建议实施分页,您可以在其中分批返回结果(例如每页 50 个)。

In addition, if you are using only some of the fields from the documents, you should tell MongoDB to return only these fields, and not all of them.此外,如果您只使用文档中的某些字段,您应该告诉 MongoDB 只返回这些字段,而不是全部。 That would also increase the performance since less data will be transferred through the network.这也将提高性能,因为通过网络传输的数据更少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM