mongodb:limit() 会提高查询速度吗?

标签 mongodb

db.inventory.find().limit(10) 是否比 db.inventory.find() 快?

我在 mongodb 中有数百万条记录,我想在某些订单中获得前 10 条记录。

最佳答案

使用limit(),您通知服务器您将不会检索超过k 个文档。允许进行一些优化以减少带宽消耗并加快排序。最后,使用限制子句,服务器将能够在 RAM 中排序时更好地使用最大可用的 32MB(即:当无法从索引中获取排序顺序时)。


现在,长话短说:find() 返回一个游标。默认情况下,游标会将结果批量传输到客户端。来自 the documentation ,:

For most queries, the first batch returns 101 documents or just enough documents to exceed 1 megabyte. Subsequent batch size is 4 megabytes.

使用 limit() 游标将不需要检索比必要更多的文档。从而减少带宽消耗和延迟。

请注意,根据您的用例,您可能还会使用 sort() 操作。来自与上述相同的文档:

For queries that include a sort operation without an index, the server must load all the documents in memory to perform the sort before returning any results.

还有 sort() documentation page进一步解释:

If MongoDB cannot obtain the sort order via an index scan, then MongoDB uses a top-k sort algorithm. This algorithm buffers the first k results (or last, depending on the sort order) seen so far by the underlying index or collection access. If at any point the memory footprint of these k results exceeds 32 megabytes, the query will fail1.


132 MB 的限制并非特定于使用 limit() 子句进行排序。任何无法从索引中获取顺序的排序都会受到同样的限制。但是,对于普通 排序,服务器需要在其内存中保存所有 文档以对它们进行排序。使用有限排序,它只需同时在内存中存储k个文档。

关于mongodb:limit() 会提高查询速度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31162746/

相关文章:

mongodb - ReactiveMongo + TypeSafe Stack => 生产?

mongodb - Heroku 无法验证 mongolab

javascript - Mongoosejs 在 for 循环中使用 Promise

javascript - 使用 'moment.js' 将自定义日期戳添加到 node.js

javascript - 消息: 'Cast to number failed for value "undefined"at path in nodejs mongoose express

node.js - Node - 将 google openid 保存到 mongodb

mongodb - 为什么 MongoDB 中没有连接关系?

javascript - 为 URI 生成唯一的字符串 (JavaScript/NodeJS)

c - 在迭代 bson 时访问 value.type

python - 如何将图像保存到具有图像 url 的 mongodb?