gpt4 book ai didi

mongodb - 使用 Mongoose 跳过大量记录时如何避免内存限制?

转载 作者:可可西里 更新时间:2023-11-01 09:12:54 32 4
gpt4 key购买 nike

在一个拥有超过 10 万条记录的集合中,当我像这样使用 Mongoose 选项进行查询时:

contact.find({}, {}, {
collation: {
locale: 'en_US',
strength: 1
},
skip: 90000,
limit: 10,
sort: {
email: 1
}
});

我收到这个错误:

MongoError:查找命令期间执行器错误:OperationFailed:排序操作使用的 RAM 超过最大 33554432 字节。添加索引,或指定更小的限制。

但我确实在电子邮件字段上有一个索引:

{
"v" : 2,
"key" : {
"email" : 1
},
"name" : "email_1",
"ns" : "leadfox.contact",
"background" : true
}

另一方面,当我在 Mongo shell 中查询时,它工作正常:

db.contact.find().sort({email: 1}).skip(90000).limit(10)

最佳答案

您遇到的问题是因为 skip。正如您在 documentation 中看到的那样

The cursor.skip() method is often expensive because it requires the server to walk from the beginning of the collection or index to get the offset or skip position before beginning to return results. As the offset (e.g. pageNumber above) increases, cursor.skip() will become slower and more CPU intensive. With larger collections, cursor.skip() may become IO bound.

您应该找到更好的方法而不是跳过。当您使用 email 字段对文档进行排序时,您可以编写一个带有 email 字段的范围查询,而不是像那样skip:

contact.find({ "email": { $gt: the_last_email_from_previous_query } }, {}, {
collation: {
locale: 'en_US',
strength: 1
},
limit: 10,
sort: {
email: 1
}
});

更新:

首先。就像我上面说的,你想要的是不可能的。 Mongodb 说的,不是我说的。

其次,我建议您搜索有关现代分页方法和人们用例的信息。你在评论中的例子是荒谬的。任何用户都不应/不会直接转到第 790 页以获取任何数据。如果他们直接转到这样的页面,很可能 意味着,他们覆盖了数据直到第 790 页,他们想继续。因此,即使你正在构建一个无状态系统(就像现在所有的现代系统一样),你也应该为你的分页数据存储一些关于用户最后一个观点的信息。这是一个基于用户行为的示例方法(我不是说最好,它只是一个示例)。

另一种方法,您可以使用(像大多数现代分页表一样)您只允许用户向前或向后导航 5-6 页。因此,结合 $gt$ltemail 字段,您可以在查询中仅跳过 50-60 个文档。

另一种方法是使用其他一些工具将数据缓存在内存中。

我想你明白了。快乐编码。

关于mongodb - 使用 Mongoose 跳过大量记录时如何避免内存限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46301575/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com