Definition定义
compactAttempts to release unneeded disk space to the operating system.尝试向操作系统释放不需要的磁盘空间。
Compatibility兼容性
This command is available in deployments hosted in the following environments:此命令在以下环境中托管的部署中可用:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
Important
This command is not supported in M0 and Flex clusters. For more information, see Unsupported Commands.M0和Flex集群不支持此命令。有关详细信息,请参阅不支持的命令。
- MongoDB Enterprise
: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本 - MongoDB Community
: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本
Syntax语法
The command has the following syntax:该命令具有以下语法:
db.runCommand(
{
compact: <string>,
dryRun: <boolean>,
force: <boolean>, // Optional
freeSpaceTargetMB: <int>, // Optional
comment: <any>, // Optional
}
)Command Fields命令字段
The command takes the following fields:该命令包含以下字段:
compact | ||
dryRun |
Default: False | |
force |
| |
freeSpaceTargetMB |
Default: 20 | |
comment |
|
compact Required Privileges所需权限
For clusters enforcing authentication, you must authenticate as a user with the 对于强制身份验证的集群,您必须以用户身份对目标集合执行compact privilege action on the target collection. compact权限操作进行身份验证。The dbAdmin and hostManager roles provide the required privileges for running compact against non-system collections.dbAdmin和hostManager角色提供了对非系统集合运行compact所需的权限。
For system collections, you must:对于系统集合,您必须:
Create a custom role that grants the创建一个自定义角色,授予系统集合上的compactaction on the system collection.compact操作。Grant that role to a new or existing user.将该角色授予新用户或现有用户。Authenticate as that user to perform the以该用户身份进行身份验证以执行compactcommand.compact命令。
For example, the following operations create a custom role that grants the 例如,以下操作创建了一个自定义角色,该角色对指定的数据库和集合授予compact action against the specified database and collection:compact操作:
use admin
db.createRole(
{
role: "myCustomCompactRole",
privileges: [
{
resource: { "db" : "<database>" , "collection" : "<collection>" },
actions: [ "compact" ]
}
],
roles: []
}
)
For more information on configuring the 有关配置resource document, see Resource Document on Self-Managed Deployments.resource文档的更多信息,请参阅关于自我管理部署的资源文档。
To add the 要将dbAdmin, hostManager, or the custom role to an existing user, use db.grantRolesToUser() or db.updateUser(). dbAdmin、hostManager或自定义角色添加到现有用户,请使用db.grantRolesToUser()或db.updateUser()。The following operation grants the custom 以下操作将自定义compact role to the myCompactUser on the admin database:compact角色授予admin数据库上的myCompactUser:
use admin
db.grantRolesToUser("myCompactUser", [ "dbAdmin" | "myCustomCompactRole" ] )
To add the 要将dbAdmin or the custom role to a new user, specify the role to the roles array of the db.createUser() method when creating the user.dbAdmin或自定义角色添加到新用户,请在创建用户时将角色指定到db.createUser()方法的roles数组中。
use admin
db.createUser(
{
user: "myCompactUser",
pwd: "myCompactUserPassword",
roles: [
{ role: "dbAdmin", db: "<database>" } | "myCustomCompactRole"
]
}
)Behavior行为
Monitoring Progress监控进度
To check the 要检查compact operation's progress, monitor the mongod log file or run db.currentOp() from another shell instance.compact操作的进度,请监视mongod日志文件或从另一个shell实例运行db.currentOp()。
Operation Termination运营终止
If you terminate 如果使用compact with the db.killOp() method or restart the server before the operation finishes, compact ends and may fail its attempt to release disk space back to the operating system.db.killOp()方法终止compact,或在操作完成之前重新启动服务器,compact将结束,并可能无法将磁盘空间释放回操作系统。
Disk Space磁盘空间
The compact command attempts to reduce the disk space consumed for data and indexes in a collection by releasing obsolete blocks back to the operating system. The effectiveness of compact is relative to how many blocks are available to be released and where in the data file the blocks are.compact命令试图通过将过时的块释放回操作系统来减少集合中数据和索引所消耗的磁盘空间。compact的有效性与可释放的块数以及块在数据文件中的位置有关。
To see how the storage space changes for the collection, run the 要查看集合的存储空间如何变化,请在压缩前后运行collStats command before and after compaction. collStats命令。You can use the output metric 您可以使用输出指标collStats.freeStorageSize to view the amount of storage available for reuse.collStats.freeStorageSize查看可供重用的存储量。
The operation is iterative and operates on segments of the data file in each pass. To view an estimate of how much space 该操作是迭代式的,在每次传递中对数据文件的段进行操作。要查看压缩空间将释放多少的估计值,请使用compact will release, use the dryRun flag. Calling compact on a collection will compact both the collection and its associated indexes.dryRun标志。对集合调用compact将压缩集合及其关联索引。
compact may require additional disk space to run.可能需要额外的磁盘空间才能运行。
Performance Considerations性能注意事项
Compaction regularly checkpoints the database, which can lead to synchronization overhead. On high-traffic databases, this can potentially delay or prevent operational tasks such as taking backups. To avoid unexpected disruptions, disable compaction before taking a backup.压缩会定期检查数据库,这可能会导致同步开销。在高流量数据库上,这可能会延迟或阻止备份等操作任务。为避免意外中断,请在备份前禁用压缩。
Replica Sets复制集
You can use 您可以对存储在副本集中的集合和索引使用compact on collections and indexes that are stored in a replica set, however there are some important considerations:compact,但有一些重要的考虑因素:
The primary node does not replicate the主节点不会将compactcommand to the secondaries.compact命令复制到次节点。You should run您应该尽可能在辅助节点上运行compacton secondary nodes whenever possible. If you cannot runcompacton secondaries, see the force option.compact。如果无法在次级上运行compact,请参阅force选项。Starting in MongoDB 6.1.0 (and 6.0.2):从MongoDB 6.1.0(和6.0.2)开始:A secondary node can replicate while辅助节点可以在compactis running.compact运行时进行复制。Reads are permitted.允许阅读。
To run 在集群上运行compact on a clustercompact
Compact the secondary nodes.压缩次要节点。
Run 在其中一个辅助节点上运行compact on one of the secondary nodes. When compact finishes, repeat the operation on each of the remaining secondaries in turn.compact。当compact完成时,依次对剩余的每个次级重复该操作。
Reassign the primary node.重新分配主节点。
To step down the current primary and trigger an election, use the 要退出当前的初选并触发选举,请使用rs.stepDown() method. rs.stepDown()方法。To nominate a particular secondary node, adjust the member priority.要指定特定的辅助节点,请调整成员优先级。
Version Specific Considerations for Secondary Nodes次要节点的版本特定注意事项
A secondary node can replicate while辅助节点可以在compactis running.compact运行时进行复制。Reads are permitted.允许阅读。
While the 当compact command is running, the replica set remains in a SECONDARY status.compact命令运行时,副本集仍处于SECONDARY状态。
For more information about replica set member states, see See Replica Set Member States.有关副本集成员状态的详细信息,请参阅副本集成员状态。
For replica set maintenance and availability, see Perform Maintenance on Self-Managed Replica Set Members.有关副本集维护和可用性,请参阅对自我管理的副本集成员执行维护。
Sharded Clusters分片集群
compact only applies to 仅适用于mongod instances. In a sharded environment, run compact on each shard separately as a maintenance operation.mongod实例。在分片环境中,作为维护操作,分别在每个分片上运行compact。
You cannot issue 您不能对compact against a mongos instance.mongos实例发出compact。
Index Building建立索引
mongod rebuilds all indexes in parallel following the 按照compact operation.compact操作并行重建所有索引。
Concurrent Compact Commands Not Allowed不允许并发压缩命令
If you try to run multiple concurrent 如果您尝试在同一集合上运行多个并发compact commands on the same collection, MongoDB returns an error.compact命令,MongoDB将返回错误。
Example示例
Compact a Collection压缩集合
The following operation runs the 以下操作在compact command on the movies collection:movies集上运行compact命令:
db.runCommand( { compact: "movies" } )
{ bytesFreed: 27859, ok: 1 }
Estimate Compaction估算压实度
The following operation performs a dry run of the 以下操作对compact command on the movies collection:movies集合执行compact命令的模拟运行:
db.runCommand( {
compact: "movies",
dryRun: true
} )
{ estimatedBytesFreed: 27859, ok: 1 }