Capped collections

Capped collections

Capped collections in MongoDB are fixed-size circular collections that support high performance on operations. A capped collection have a limit size which means once a capped collection reach its limit size it starts deleting the oldest documents in the collection without providing any explicit commands. A capped collection is good for storing log files, cached data, etc...

Since capped collection are fixed-size colletions, if an update or a replacement operation changes the document size, the operation will fail and you cannot delete documents from a capped collection.

Create a Capped Collection

To create a capped collection, we must use the db.createCollection() method and should be provide a limit size(in bytes) of the collections (If the size field is less than or equal to 4096, then the collection will have a cap of 4096 bytes. Otherwise, MongoDB will raise the provided size to make it an integer multiple of 256.) and also with the capped parameter as true value. Additionally, you may also specify the maximum number of documents inside the collections but it does not replace the size parameter since this final paramter is required.

db.createCollection( "log", { capped: true, size: 100000 } )

Check if a Collection is Capped

In order to check if a collection is capped or not we will use the isCapped method as follows:

db.collection.isCapped()

Convert a Collection to Capped

Also, you can convert already created collection to a capped collection using the convertToCapped command.

db.runCommand({"convertToCapped": "mycoll", size: 100000});