English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Fixed collectionIt is a fixed-size circular collection that follows the insertion order to support high-performance creation, read, and delete operations. Circular means that when the fixed size allocated to the collection is exhausted, it will start deleting the oldest documents in the collection without any explicit command.
If an update causes the document size to increase, limit the update of documents. Since fixed collections store documents in the order of disk storage, they can ensure that the document size will not increase the allocated size on the disk. Fixed collections are most suitable for storing log information, cache data, or any other large capacity data.
To create a capped collection, we use the normal createCollection command, but we setcapped
The option is set to,true
and specify the maximum size of the collection (in bytes).
>db.createCollection("cappedLogCollection",{capped:true,size:10000})
In addition to the collection size, we can also usemax
Parameter-Limit the number of documents in the capped collection-
>db.createCollection("cappedLogCollection",{capped:true,size:10000,max:1000)
To check if a collection is capped, use the followingisCapped
Command-
>db.cappedLogCollection.isCapped()
If there is a plan to convert an existing collection to a capped one, the following code can be used to handle it-
db.runCommand({"convertToCapped":"posts",size:10000})
This code will convert our existing collectionposts
For capped collections.
By default, the search query on a capped collection will display results in the order of insertion. However, if you want to retrieve documents in reverse order, please usesort
The following commands shown in the code-
>db.cappedLogCollection.find().sort({$natural:-1)
There are some other important points about capped collections-
We cannot delete documents from a capped collection.
There is no default index on a capped collection, not even on the _id field.
When inserting a new document, MongoDB does not need to actually find a location on the disk to store the new document. It can simply insert the new document at the end of the collection. This makes insert operations in the capped collection very fast.
Similarly, when reading documents, MongoDB returns documents in the same order as they are stored on disk. This makes read operations very fast.