MongoDB Capped Collections

MongoDB Capped Collections are high-performance collections with a fixed size. For 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!


Create Capped Collection

We create a capped collection via createCollection, and set the capped option to true:

>db.createCollection("cappedLogCollection",{capped:true,size:10000})

You can also specify the number of documents by adding the max:1000 property:

>db.createCollection("cappedLogCollection",{capped:true,size:10000,max:1000})

Check whether a collection is a capped collection:

>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.


Query Capped Collection

Documents in a capped collection are stored in insertion order. By default, queries return in insertion order, and 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 dropping, you need to explicitly recreate the collection.

On a 32-bit machine, the maximum size of a capped collection is about 482.5M; on 64-bit, it is only limited by the system file size.


Capped Collection Properties and Usage

Properties

  • Property 1: Insertion into a capped collection is extremely fast.
  • Property 2: Query output in insertion order is extremely fast.
  • Property 3: When inserting the latest data, it can eliminate the oldest data.

Usage

  • Usage 1: Store log information.
  • Usage 2: Cache a small number of documents.
Other extensions