对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

游标.allowDiskUse()(mongosh方法)

cursor.allowDiskUse()

重要

mongosh 方法

This page documents a mongosh method. This is not the documentation for a language-specific driver, such as Node.js.

如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。

allowDiskUse()当管道阶段超过100 兆字节限制时,使用 允许或禁止在磁盘上写入临时文件。从MongoDB.6 0开始,需要大于100 MB 内存的操作默认会自动写入临时文件。

allowDiskUse() 采用以下形式:

db.collection.find(<match>).sort(<sort>).allowDiskUse()

有关内存中排序操作的更多信息,请参阅排序和索引使用

此方法可用于以下环境中托管的部署:

  • MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务

注意

所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令

从 MongoDB 6.0 开始,需要 100 MB 以上内存容量的管道阶段默认将临时文件写入磁盘。

注意

在 MongoDB 6.0 之前,.allowDiskUse(false).allowDiskUse(true) 具有相同的效果。在 MongoDB 6.0 中,mongosh 和旧版 mongo Shell 在以下方面表现一致:

如果 allowDiskUseByDefaulttrue(这是默认值):

  • .allowDiskUse() 没有额外作用

  • .allowDiskUse(true) 没有额外作用

  • .allowDiskUse(false) 禁止查询将临时文件写入磁盘

如果 allowDiskUseByDefaultfalse

  • .allowDiskUse() 支持将临时文件写入磁盘

  • .allowDiskUse(true) 支持将临时文件写入磁盘

  • .allowDiskUse(false) 没有额外作用

cursor.allowDiskUse()对使用索引应答的排序操作或需要少于100 MB 内存的非索引(“内存中”)排序操作没有影响。有关内存中排序和排序索引使用的更完整文档,请参阅排序和索引使用。

如要检查 MongoDB 是否必须执行内存中排序,请在查询中添加 cursor.explain() 并检查解释结果。如果查询计划包含 SORT 阶段,则 MongoDB 必须执行受 100 MB 内存限制的内存排序操作。

考虑一个集合 sensors,仅其默认索引位于 _id。该集合包含类似于以下内容的文档:

{
"sensor-name" : "TEMP-21425",
"sensor-location" : "Unit 12",
"reading" : {
"timestamp" : Timestamp(1580247215, 1),
"value" : 212,
"unit" : "Fahrenheit"
}
}

The following operation includes a cursor.sort() on the field reading.timestamp. The operation also passes false to cursor.allowDiskUse() to prohibit the query from writing temporary files to disk.

db.sensors.find({"sensor-location" : "Unit 12"}).
sort({"reading.timestamp" : 1}).
allowDiskUse(false)

由于索引中不包含 reading.timestamp,因此 MongoDB 必须执行内存中排序操作才能按请求的排序顺序返回结果。通过指定 cursor.allowDiskUse(false),如果排序操作需要超过 100 MB 的系统内存,MongoDB 将无法处理。如果操作需要超过 100 MB 的系统内存,则 MongoDB 将返回错误。

给本页内容打分