MongoDB Capped Collections - MongoDB

What are capped collections?

Capped collections in MongoDB are fixed-size circular collections which follow the insertion order to support high performance to create, read, and delete operations. By circular, this means that when fixed size allocated to the collection gets exhausted, it starts deleting the oldest document in the collection without providing any explicit commands.

A capped collection restricts updates to the documents if the update results in increased document size. As capped collections store documents in the order of the disk storage, it makes sure that the document size does not increase the size allocated on the disk. Capped collections are good for storing log information, cache data, or any other high volume data.

Creating Capped Collection

For creating a capped collection, you can use normal createCollection command but with capped option as true and specifying the maximum size of collection in bytes.

In addition to collection size, you can also limit the number of documents in the collection using the max parameter

To check if a collection is capped or not, use below isCapped command

If are planning to convert an existing collection to capped, you can do it with below code

This code will convert the existing collection posts to a capped collection.

Querying Capped Collection

By default, a find query on a capped collection will display results in insertion order. But if you want the documents to be retrieved in reverse order, use sort command as shown in below code

Points to be remembered regarding capped collections

  • Documents cannot be deleted from a capped collection.
  • There are no default indexes present in a capped collection, not even on _id field.
  • While inserting a new document, MongoDB will not have to actually look for a place for accommodating a new document on the disk. It will blindly insert the new document at the tail of the collection. This makes insert operations in capped collectionsvery quick.
  • Similarly, while reading documents MongoDB will return the documents in the same order as present on the disk and this makes the read operation very quick.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

MongoDB Topics