MongoDB Capped Collections
MongoDB Capped Collections are high-performance collections with a fixed size. With a fixed size, we can imagine it as a circular queue; when the collection space is used up, newly inserted elements will overwrite the original head elements!
Creating a capped collection
We create a capped collection through createCollection, with the capped option set to true:
>db.createCollection("cappedLogCollection",{capped:true,size:10000})
You can also specify the number of documents by adding the max:1000 attribute:
>db.createCollection("cappedLogCollection",{capped:true,size:10000,max:1000})
Determine whether a collection is capped:
>db.cappedLogCollection.isCapped()
If you need 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.
Capped collection queries
Capped collection documents are stored in insertion order. By default, queries return in insertion order, but you can also use $natural to adjust the return order.
>db.cappedLogCollection.find().sort({$natural:-1})
Features of capped collections
You can insert and update, but updates cannot exceed the size of the collection, otherwise the update fails. Deletion is not allowed, but you can call drop() to delete all rows in the collection; however, after drop you need to explicitly rebuild the collection.
On 32-bit machines, the maximum size of a cappped collection is about 482.5M; on 64-bit it is only limited by the system file size.
Capped collection properties and usage
property
- Property 1: Insertion into a capped collection is extremely fast
- Property 2: Query output in insertion order is extremely fast
- Property 3: Able to discard the oldest data when inserting the latest data
Usage
- Usage 1: Store log information
- Usage 2: Cache a small number of documents