To create a capped collection, specify the 要创建封顶集合,请在capped option to either the db.createCollection() method or the create command.db.createCollection()方法或create命令中指定capped选项。
You must create capped collections explicitly. You cannot create a capped collection implicitly by inserting data into a non-existing collection.您必须显式创建封顶集合。您不能通过将数据插入不存在的集合来隐式创建封顶集合。
When you create a capped collection you must specify the maximum size of the collection. MongoDB pre-allocates the specified storage for the collection. The size of the capped collection includes a small amount of space for internal overhead.创建封顶集合时,必须指定集合的最大大小。MongoDB为集合预分配指定的存储空间。封顶集合的大小包括少量的内部开销空间。
You can optionally specify a maximum number of documents for the collection. MongoDB removes older documents if the collection reaches the maximum size limit before it reaches the maximum document count.您可以选择为集合指定最大文档数。如果集合在达到最大文档计数之前达到最大大小限制,MongoDB会删除旧文档。
About this Task关于此任务
Generally, TTL (Time To Live) indexes offer better performance and more flexibility than capped collections. TTL indexes expire and remove data from normal collections based on the value of a date-typed field and a TTL value for the index.通常,TTL(生存时间)索引比封顶集合提供更好的性能和更大的灵活性。TTL索引过期,并根据日期类型字段的值和索引的TTL值从正常集合中删除数据。
Capped collections serialize write operations and therefore have worse concurrent insert, update, and delete performance than non-capped collections. Before you create a capped collection, consider if you can use a TTL index instead.封顶集合序列化写操作,因此与非封顶集合相比,其并发插入、更新和删除性能较差。在创建封顶集合之前,请考虑是否可以使用TTL索引。
Steps步骤
The following examples show you how to:以下示例向您展示了如何:
Create a Capped Collection with a Maximum Size创建具有最大大小的封顶集合Create a Capped Collection with a Maximum Number of Documents创建具有最大文档数的封顶集合
Create a Capped Collection with a Maximum Size创建具有最大大小的封顶集合
Create a capped collection called 创建一个名为log that has a maximum size of 100,000 bytes:log的封顶集合,最大大小为100000字节:
db.createCollection( "log", { capped: true, size: 100000 } )
Note
The value that you provide for the 为size field must be greater than 0 and less than or equal to 1024^5 (1 PB). size字段提供的值必须大于0且小于或等于1024^5(1 PB)。MongoDB rounds the MongoDB将所有封顶集合的size of all capped collections up to the nearest integer multiple of 256, in bytes.size四舍五入到最接近的256的整数倍(以字节为单位)。
Create a Capped Collection with a Maximum Number of Documents创建具有最大文档数的封顶集合
Create a capped collection called 创建一个名为log2的封顶集合,其最大大小为5242880字节,最多可存储5000个文档:log2 that has a maximum size of 5,242,880 bytes and can store a maximum of 5,000 documents:
db.createCollection(
"log2",
{
capped: true,
size: 5242880,
max: 5000
}
)
Important
The 即使指定了最大文档数size field is always required, even when you specify the max number of documents.max,size字段也始终是必需的。