在集群中增加或者删除分片

  • 在集群中增加分片时,由于新的分片上并没有数据块,会造成数据的不均衡.此时MongoDB会立即开始向新分片迁移数据,集群达到数据均衡的状态需要花费一些时间.

  • 当删除一个分片时,均衡器需要将被删除的分片上的数据全部迁移到其他分片上,在全部迁移结束且元信息更新完毕之后,你可以安全地将这个分片移除.

  • 对集合进行分片时,你需要选择一个 片键 , shard key 是每条记录都必须包含的,且建立了索引的单个字段或复合字段,MongoDB按照片键将数据划分到不同的 数据块 中,并将 数据块 均衡地分布到所有分片中.为了按照片键划分数据块,MongoDB使用 基于范围的分片方式 或者 基于哈希的分片方式 ,参见 片键 获得更多信息.


  • How frequently does MMAPv1 write to disk?¶

In the default configuration for the MMAPv1 storage engine, MongoDB writes to the data files on disk every 60 seconds and writes to the journal files roughly every 100 milliseconds.

  • 为什么目录里面的文件比我的数据库还要大?

默认存储目录 /data/db 中的数据文件可能会比数据库中的数据大,思考一下下面可能的原因:

Preallocated data files

MongoDB preallocates its data files to avoid filesystem fragmentation, and because of this, the size of these files do not necessarily reflect the size of your data.

The storage.mmapv1.smallFiles option will reduce the size of these files, which may be useful if you have many small databases on disk.

在类Unix系统中, mongod 预先配置了一个另外的数据文件并将磁盘空间初始化为0。当创建一个新的数据库时,预配置文件对于避免延迟有非常大的作用。

你可以通过 preallocDataFiles 设置将预配置设为 false。但是千万不要设置 preallocDataFiles ,只需使用 preallocDataFiles 调试你经常删除的小数据库。

The default allocation is approximately 5% of disk space on 64-bit installations. In most cases, you should not need to resize the oplog. See Oplog Sizing for more information.

  • The journal

如果 mongod 是复制集成员,数据目录包括 local 数据库中 固定集合 的 oplog.rs 文件。在64位安装包中,默认分配空间大约为磁盘空间的5%,通过 ` 查看更多信息。在大部分实例中,你不需要调整oplog的大小。当然,如果你想调整,可以查看 修改Oplog大小。

  • Empty records

数据目录含有journal文件,它将MongoDB在操作数据库中的写入操作存储在磁盘上。查看 Journaling。

To allow MongoDB to more effectively reuse the space, you can de-fragment your data. To de-fragment, use the compact command. The compact requires up to 2 gigabytes of extra disk space to run. Do not use compact if you are critically low on disk space. For more information on its behavior and other considerations, see compact.

当删除文档和集合时,MongoDB将会继续列出数据文件中的空记录。MongoDB可以重复使用这部分空间,但是不会释放这部分空间给操作系统。

  • repairDatabase

You can use repairDatabase on a database to rebuilds the database, de-fragmenting the associated storage in the process.

使用 repairDatabase 重置存储来重建数据库可以再次利用删除的空间。 repairDatabase 需要至少2G额外磁盘空间来运行。如果磁盘空间较少,禁止使用 repairDatabase。

  • 警告

Do not use repairDatabase if you are critically low on disk space.

当使用 repairDatabase 进行修复时,需要足够的磁盘空间来支持新旧数据库。可以使用 repairDatabase 锁定其它操作,可能需要一定的时间。