定义
cursor.allowDiskUse()重要
mongosh 方法
This page documents a
mongoshmethod. This is not the documentation for a language-specific driver, such as Node.js.如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。
Use
allowDiskUse()to either allow or prohibit writing temporary files on disk when a pipeline stage exceeds the 100 megabyte limit. Starting in MongoDB 6.0, operations that require greater than 100 megabytes of memory automatically write data to temporary files by default.allowDiskUse()采用以下形式:db.collection.find(<match>).sort(<sort>).allowDiskUse()
有关内存中排序操作的更多信息,请参阅排序和索引使用。
兼容性
此方法可用于以下环境中托管的部署:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
注意
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
行为
互动 allowDiskUseByDefault
从 MongoDB 6.0 开始,需要 100 MB 以上内存容量的管道阶段默认将临时文件写入磁盘。
注意
在 MongoDB 6.0 之前,.allowDiskUse(false) 和 .allowDiskUse(true) 具有相同的效果。在 MongoDB 6.0 中,mongosh 和旧版 mongo Shell 在以下方面表现一致:
如果 allowDiskUseByDefault 为 true(这是默认值):
.allowDiskUse()没有额外作用.allowDiskUse(true)没有额外作用.allowDiskUse(false)禁止查询将临时文件写入磁盘
如果 allowDiskUseByDefault 为 false:
.allowDiskUse()支持将临时文件写入磁盘.allowDiskUse(true)支持将临时文件写入磁盘.allowDiskUse(false)没有额外作用
仅支持大型非索引排序
cursor.allowDiskUse() has no effect on sort operations answered using an index or non-indexed ("in-memory") sort operations which require less than 100 megabytes of memory. For more complete documentation on in-memory sorts and sort index use, see Sort and Index Use.
如要检查 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 将返回错误。