On this page
convertToCapped
在本页面
convertToCapped
Do Not Run This Command In Sharded Clusters
MongoDB 不支持分片群集中的convertToCapped命令。
convertToCapped命令将同一数据库中现有的,无上限的集合转换为capped collection。
该命令具有以下语法:
{ convertToCapped: <collection>, size: <capped size> , writeConcern: <document>}
该命令包含以下字段:
Field | Description |
---|---|
convertToCapped | 要转换的现有集合的名称。 |
size | 上限集合的最大大小(以字节为单位)。 |
writeConcern | 可选的。表示drop命令的write concern的文档。省略使用默认的写关注。 |
convertToCapped获取一个现有的集合(<collection>
),并将其转换为最大大小(以字节为单位)的上限集合,该上限由size
参数(<capped size>
)指定。
在转换过程中,convertToCapped命令表现出以下行为:
MongoDB 在natural order中遍历原始集合中的文档,并将这些文档加载到新的带上限的集合中。
如果为上限集合指定的
capped size
小于原始未上限集合的大小,则 MongoDB 将根据插入 Sequences 或“先进先出”Sequences 覆盖上限集合中的文档。在内部,为了转换集合,MongoDB 使用以下过程
cloneCollectionAsCapped命令创建上限集合并导入数据。
MongoDB 删除原始集合。
renameCollection将新的带上限的集合重命名为原始集合的名称。
在操作期间,它将持有数据库排他锁。锁定同一数据库的其他操作将被阻止,直到该操作完成。有关锁定数据库的操作,请参见一些常见的 Client 端操作会采取什么锁?。
Warning
convertToCapped不会从新集合上的原始集合重新创建索引,而_id
字段上的索引除外。如果需要此集合上的索引,则转换完成后,需要创建这些索引。
Example
转换收藏集
下面的示例使用db.collection.save()操作创建events
集合,并使用db.collection.stats()获取有关该集合的信息:
db.events.save( { click: 'button-1', time: new Date() } )
db.events.stats()
MongoDB 将返回以下内容:
{
"ns" : "test.events",
...
"capped" : false,
...
}
要将events
集合转换为上限集合并查看更新的集合信息,请运行以下命令:
db.runCommand( { convertToCapped: 'events', size: 8192 } )
db.events.stats()
MongoDB 将返回以下内容:
{
"ns" : "test.events",
...
"capped" : true,
"max" : NumberLong("9223372036854775807"),
"maxSize" : 8192,
...
}
convertToCapped不会从新集合上的原始集合重新创建索引,而_id
字段上的索引除外。如果需要此集合上的索引,则转换完成后,需要创建这些索引。
See also