Database Manual / Reference / Database Commands / Administration

compact (database command数据库命令)

Definition定义

compact
Attempts 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:该命令包含以下字段:

Field字段Type类型Description描述
compactstring字符串The name of the collection.集合的名称。
dryRunboolean布尔值

New in version 8.0.在版本8.0中新增。

If enabled, the compact command returns an estimate of how much space, in bytes, compaction can reclaim from the targeted collection. If you run compact with dryRun set to true, MongoDB only returns the estimated value and does not perform any kind of compaction.如果启用,compact命令将返回压缩可以从目标集合中回收多少空间(以字节为单位)的估计值。如果你在dryRun设置为true的情况下运行compact,MongoDB只会返回估计值,不会执行任何类型的压缩。

Default: False

forceboolean布尔值

Optional. 可选。If enabled, forces compact to run on the primary in a replica set. 如果启用,则强制compact在副本集中的primary上运行。compact does not block MongoDB CRUD Operations on the database it is compacting.不会阻止正在压缩的数据库上的MongoDB CRUD操作

freeSpaceTargetMBInteger整数

Optional. 可选。Specifies the minimum amount of storage space, in megabytes, that must be recoverable for compaction to proceed.指定压缩必须可恢复的最小存储空间量(以兆字节为单位)。

Default: 20

commentany任意

Optional. 可选。A user-provided comment to attach to this command. Once set, this comment appears alongside records of this command in the following locations:用户提供了要附加到此命令的注释。设置后,此注释将与此命令的记录一起出现在以下位置:

A comment can be any valid BSON type (string, integer, object, array, etc).注释可以是任何有效的BSON类型(字符串、整数、对象、数组等)。

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.dbAdminhostManager角色提供了对非系统集合运行compact所需的权限。

For system collections, you must:对于系统集合,您必须:

  1. Create a custom role that grants the compact action on the system collection.创建一个自定义角色,授予系统集合上的compact操作。
  2. Grant that role to a new or existing user.将该角色授予新用户或现有用户。
  3. Authenticate as that user to perform the compact command.以该用户身份进行身份验证以执行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(). 要将dbAdminhostManager或自定义角色添加到现有用户,请使用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 compact command to the secondaries.主节点不会将compact命令复制到次节点。
  • You should run compact on secondary nodes whenever possible. If you cannot run compact on 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 compact is running.辅助节点可以在compact运行时进行复制。
    • Reads are permitted.允许阅读。

To run compact on a cluster在集群上运行compact

1

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完成时,依次对剩余的每个次级重复该操作。

2

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.要指定特定的辅助节点,请调整成员优先级

3

Compact the old primary.压缩旧的主。

After stepping down, the old primary node becomes a secondary node. Run compact on the old primary node.下台后,旧的主节点将成为辅助节点。在旧的主节点上运行compact

Version Specific Considerations for Secondary Nodes次要节点的版本特定注意事项

  • A secondary node can replicate while compact is 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 }

Learn More了解更多