对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

convertToCapped(数据库命令)

convertToCapped

警告

不要对分片collection运行此命令

MongoDB does not support the convertToCapped command on sharded collections.

The convertToCapped command converts an existing, non-capped collection to a capped collection within the same database.

此命令可用于以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

该命令具有以下语法:

db.runCommand(
{
convertToCapped: <collection>,
size: <capped size>,
writeConcern: <document>,
comment: <any>
}
)

该命令接受以下字段:

字段
说明

convertToCapped

要转换的现有collection的名称。

size

固定大小集合的最大大小(以字节为单位)。

writeConcern

可选。 表达 命令 写关注(write concern) drop的文档。省略以使用默认的写关注(write concern)。

comment

可选。用户提供的待附加到该命令的注释。设置后,该注释将与该命令的记录一起出现在以下位置:

注释可以是任何有效的 BSON 类型(字符串、整型、对象、数组等)。

convertToCapped takes an existing collection (<collection>) and transforms it into a capped collection with a maximum size in bytes, specified by the size argument (<capped size>).

During the conversion process, the convertToCapped command exhibits the following behavior:

  • MongoDB 按存储顺序遍历原始collection中的文档,并将这些文档加载到新的固定大小集合中。

  • 如果为固定大小集合指定的capped size小于原始非固定大小collection的大小,则 MongoDB 将根据插入顺序或先进先出顺序覆盖固定大小集合中的文档。

  • 在内部,为了转换collection,MongoDB 使用以下过程

    • cloneCollectionAsCapped 命令会创建固定大小集合并导入数据。

    • MongoDB 会删除原始collection。

    • renameCollection 将新的固定大小集合重命名为原始集合的名称。

  • 此功能会在操作期间保持数据库独占锁。锁定同一数据库的其他操作将被阻止,直到该操作完成。请参阅某些常见客户端操作会采用哪些锁?锁定数据库的操作。

警告

The convertToCapped will not recreate indexes from the original collection on the new collection, other than the index on the _id field. If you need indexes on this collection you will need to create these indexes after the conversion is complete.

以下示例使用db.collection.insertOne() events创建collection,并使用db.collection.stats() 获取有关该collection的信息:

db.events.insertOne( { 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" : Long("9223372036854775807"),
"maxSize" : 8192,
...
}

The convertToCapped will not recreate indexes from the original collection on the new collection, other than the index on the _id field. If you need indexes on this collection you will need to create these indexes after the conversion is complete.

提示

create

给本页内容打分