MongoDB Capped Collections
MongoDB Capped Collections are high-performance collections with a fixed size. Imagine them as a circular queue: when the collection space is exhausted, new elements inserted will overwrite the earliest elements at the head of the queue!
Creating Capped Collections
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 number of documents with the max: 1000
attribute:
>db.createCollection("cappedLogCollection", {capped: true, size: 10000, max: 1000})
To check if a collection is capped:
>db.cappedLogCollection.isCapped()
If you need to convert an existing collection to a capped collection, use the following command:
>db.runCommand({convertToCapped: "posts", size: 10000})
The above code converts our existing posts
collection into a capped collection.
Querying Capped Collections
Capped collection documents are stored in insertion order. By default, queries return documents in insertion order, but you can adjust the return order using $natural
.
>db.cappedLogCollection.find().sort({$natural: -1})
Features of Capped Collections
You can insert and update documents, but updates cannot exceed the collection's size, or they will fail. Deletion is not allowed, but you can call drop()
to delete all rows in the collection. After dropping, you need to explicitly recreate the collection.
On a 32-bit machine, the maximum size of a capped collection is approximately 482.5MB. On a 64-bit machine, the size is limited only by the system file size.
Attributes and Usage of Capped Collections
Attributes
- Attribute 1: Extremely fast insertion speed
- Attribute 2: Very fast query output in insertion order
- Attribute 3: Ability to evict the oldest data when inserting new data
Usage
- Usage 1: Storing log information
- Usage 2: Caching a small number of documents