Mongodb Capped Collections
# MongoDB Capped Collections
MongoDB Capped Collections are high-performance collections with a fixed size. We can imagine them as a circular queue. When the collection space is full, newly inserted elements will overwrite the oldest elements at the head of the queue!
* * *
## Creating a Capped Collection
We create a capped collection using `createCollection` with the `capped` option set to `true`:
>db.createCollection("cappedLogCollection",{capped:true,size:10000})
You can also specify the maximum number of documents by adding the `max` attribute:
>db.createCollection("cappedLogCollection",{capped:true,size:10000,max:1000})
To check if a collection is capped:
>db.cappedLogCollection.isCapped()
To convert an existing collection to a capped collection, you can use the following command:
>db.runCommand({"convertToCapped":"posts",size:10000})
The above code converts our existing `posts` collection into a capped collection.
* * *
## Querying a Capped Collection
Documents in a capped collection are stored in insertion order. By default, queries return documents in this order. You can also use `$natural` to reverse the order.
>db.cappedLogCollection.find().sort({$natural:-1})
* * *
## Features of Capped Collections
You can insert and update documents, but updates cannot exceed the collection's size limit, otherwise the update will fail. Deletion is not allowed, but you can call `drop()` to delete all rows in the collection. After dropping, you must explicitly recreate the collection.
On a 32-bit system, the maximum size of a capped collection is approximately 482.5 MB. On a 64-bit system, it is only limited by the system's file size.
* * *
## Capped Collection Properties and Usage
### Properties
* Property 1: Extremely fast insertion speed for capped collections.
* Property 2: Extremely fast query output speed in insertion order.
* Property 3: Can automatically evict the oldest data when inserting the latest data.
### Usage
* Usage 1: Storing log information.
* Usage 2: Caching a small number of documents.
YouTip