MongoDB – Capped Collections | How to Create it | Advantages and Disadvantages

If You are interested to learn about the Rockmongo

Capped collections are circular collections with fixed sizes that adhere to the insertion order in order to provide fast create, read, and delete operations. By circular, it is meant that when the collection’s allotted fixed size is reached, it will begin silently eliminating each document in turn, starting with the oldest one.

Updates to the documents that result in larger documents are prohibited by capped collections. Capped collections ensure that the document size does not exceed the size allotted on the disc since they keep documents in the order of the disc storage. For storing log data, cache data, or any other high volume data, capped collections work best.

Syntax:

db.createCollection(<name>, {capped: <boolean>, autoIndexId: <boolean>, size: <number>, max: <number>, storageEngine: <document>, validator: <document>, validationLevel: <string>, validationAction: <string>, indexOptionDefaults: <document>, viewOn: <string>, pipeline: <pipeline>, collation: <document>, writeConcern: <document>})

Creating Capped Collection

To create a capped collection, we use the normal createCollection command but with capped option as true and specifying the maximum size of collection in bytes.

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

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

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

If you want to check whether a collection is capped or not, use the following isCapped command −

>db.cappedLogCollection.isCapped()

If there is an existing collection which you are planning to convert to capped, you can do it with the following code −

>db.runCommand({"convertToCapped":"posts",size:10000})

This code would convert our existing collection posts to a capped collection.

Querying Capped Collection

By default, the outcomes of a find query on a capped collection are shown in insertion order. However, you can use the sort command as demonstrated in the following code to obtain the documents in reverse order.

>db.cappedLogCollection.find().sort({$natural:-1})

There are a few additional crucial details about capped collections that are worth noting.

  • A capped collection does not allow for document deletion.
  • A capped collection doesn’t have any default indexes, not even on the _id field.
  • MongoDB does not need to physically search for space on the disc to accommodate new documents when inserting them.
  • The new document may be blindly inserted at the end of the collection. Due to this, insert operations in capped collections are extremely quick.

Similar to how it reads documents from disc, MongoDB returns the documents in the same sequence. The read process is quite quick as a result.

How to remove capped collection in MongoDB?

A capped collection does not allow document deletion. When the collection’s allotted size has been reached, it can only be removed automatically following the inclusion of new documents. MongoDB returns the same document in the same order that it was present on disc after reading the documents from a capped collection.

How to check if collection is capped in MongoDB?

The isCapped() method in MongoDB allows us to determine whether the collection has a cap or not. If the supplied collections are capped collections, this method returns true. If not, return false.

Parameters:

name: It is a string that represents the collection’s name.

It is a parameter with an optional value.

Optional parameters:

  • Capped: Capped collections are made with this. If this field’s value is true, the size field must contain the maximum size. It is boolean in nature.
  • autoIndexId: If this field’s value is false, an index on the _id field won’t be automatically created. It is boolean in nature.
  • size: It provides the collection’s maximum size in bytes. It is a number, after all.
  • max:
  • It details the most papers that can be included in the capped collection. It is a number, after all.
  • storageEngine: Only the WiredTiger storage engine is compatible with it. It is a document, after all.
  • Validator: It details the collection’s validation policies. It is a document, after all.
  • ValidationLevel: This shows how rigorously MongoDB enforces the validity rule on the original document when performing updates. It’s a string, after all.
  • ValidationAction: It shows whether to raise an error on invalid documents or only issue a warning about the infractions while allowing the insertion of erroneous documents. It’s a string, after all.
  • When building a collection, the user can set the default configuration for indexes using the indexOptionDefaults option. It is a type of document.
  • viewOn: The name of the source collection or view that the view will be derived from. It’s a string, after all.
  • pipeline: The phases of the aggregate pipeline are contained in this array. Alternatively, we can apply pipeline to the view or viewOne collection using this option. It is a type of array.
  • collation: It identifies the collection’s default collation. It is a document, after all.
  • writeConcern: It conveys the writer’s level of worry about the operation. Avoid this argument unless you want to utilise the default write concern. It is a type of document.

Examples:

In the following example, we are working with the “gfg” database in which we are creating a new capped collection of name “student” with maximum document capacity “4” using createCollection() method.

db.createCollection("student", {capped:true, size:10000, max:4})

Now we insert the documents in the student collection:

After insert documents, we will display all the documents present in the student collection using find() method.

Now, if we try to insert one more document, it will override the existing document. In the example, we are inserting a new document with the name Akash that overrides the existing document with the name Mihir:

After inserting one or more document:

How to check if the collection is capped or not?

We can check whether the collection is capped or not with the isCapped() method in MongoDB. This method returns true is the specified collections capped collection. Otherwise, return, false.

Syntax:

db.Collection_name.isCapped()

Example:

db.student.isCapped()

After convert student collection to a capped:

How to convert a collection to a capped?

If there is an existing collection that we want to change it to capped, we can do it using the convertToCapped command. It changes the current collection to capped collection:

Syntax:

    convertToCapped: <collection>,

    size: <capped size>,

    writeConcern: <document>,

    comment: <any>

}

Example:

db.runCommand({"convertToCapped":"student",size:5000})

Before convert to capped:

After convert to capped:

Advantages of Capped Collections

  • Queries do not require an index to return documents in insertion order since it offers higher insertion throughput.
  • For the purpose of preventing the document from shifting positions on the disc, capped collections only permit updates that are the same size as the original document.
  • Log files are useful to have.

Disadvantages of Capped Collections

  • If the update of a document is larger than the collection’s initial size, the update operation fails.
  • Documents in capped collections cannot be deleted. Use the following command to remove every record from a capped collection:
{ emptycapped: Collection_name }
  • Capped collection cant be shard.
MongoDB – Capped Collections | How to Create it | Advantages and Disadvantages
Show Buttons
Hide Buttons