mongodb compact

在2.0以后,可以使用compact对集合进行压缩,释放空间,这个类似于repairdatabase,但是repairdatabase只能对整个数据库进行压缩,所以在效率和速度上,compact更快,也不会需要那么多的磁盘空间。
         运行格式如下:
> db.runCommand( { compact : 'mycollectionname' } )
> // or
> db.mycollection.runCommand( "compact" )

Options

  • force:true Because this blocks all other activity (in v2.2, only for its database), the compact command returns an error when invoked on a replica set primary. Use force:true to run on a replica set primary.
  • paddingFactor:<pf> (v2.2+). Specify a padding factor for the compacted documents. By default the documents are fully compacted with no padding. If you do updates on the documents which grow them, and especially if you have several indexes for the collection, you will want some padding. Default is 1.0 (no padding), maximum 4.0.
  • paddingBytes:<bytes> (v2.2+.) Specify padding as an absolute number of bytes. Can be useful if your documents start at small but then grow a large amount; for example if they start 40 bytes long and then you grow then by 1KB, paddingBytes:1024 might be reasonable whereas paddingFactor:4.0 would only add 40*(4.0-1)=120 bytes of padding.
  • // example. always add at least 100 bytes of padding, and at least 10% of the doc size too > db.runCommand( { compact : 'mycollectionname', paddingBytes:100, paddingFactor:1.1 } )

另外如果在replica sets中,需要注意的几点:
1.在mongodb replica sets中主节点直接运行会报错,需要加上force:true
   db.runCommand( { compact : 'mycollectionname',force:true})
2.如果在从节点运行,那么从节点状态会变成recovering状态,结束后,自动转变为secondary状态
3.在replica sets中,要分别在每个节点执行,一个节点执行了compact,其他节点并不能复制

Interrupting a compaction ---终止compact导致的一些结果

At the beginning of compaction, indexes are dropped for the collection. At the end, indexes are rebuilt. Thus, if you kill the compaction in the middle of its operation, either with killOp or a server failure, indexes may be missing from your collection. If you are running with --journal, no data should ever be lost on a crash during compaction, although on startup the indexes will not be present. (Regardless of this, always do a backup before system maintenance such as this!) When the indexes are rebuilt, they will be in the 2.0 index format.

If there's a crash while the command is running, then as long as journaling is enabled, your data will be safe.

Additionally, if a compaction operation is interrupted, much of the existing free space in a collection may become un-reusable. In this scenario, it is recommended that compaction be run again, to completion, to restore use of this free space

主要说的是索引在执行中,会重建,如果意外终止,会丢失数据,不过如果开启了journal,数据相对来说安全很多,还有就是空闲空间会变成不能重用,需要再次执行compact,恢复空闲空间的使用。

你可能感兴趣的:(mongodb compact)