Home >>MongoDB Tutorial >MongoDB Capped Collections

MongoDB Capped Collections

MongoDB Capped Collections

Capped collections are fixed-size circular collections that obey the insertion order to promote high performance for build, read, and remove operations. By circular, it means that when the fixed size allocated to the collection is exhausted, it will start deleting the oldest document in the collection without having any specific commands.

If the update results in an increased document size, capped collections limit changes to documents. Since the capped collections store documents in disk storage order, it ensures that the size of the record does not increase the size allocated to the disk. For storing log information, cache data, or any other high volume data, Capped collections are best.

Creating Capped Collection

We use the normal createCollection command to create a capped collection, but the capped option is true and specifies the maximum collection size in bytes.

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

We may also limit the number of documents in the collection by using the max parameter, in addition to the collection size.

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

If you want to check whether or not a set is restricted, use the isCapped command below –

>db.cappedLogCollection.isCapped()

You can do it with the following code if there is an existing collection that you plan to convert to capped.

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

Our existing collection posts will be converted to a capped collection through this code.

Querying Capped Collection

By default, a search on a capped collection shows the results in the order of insertion. But if you want to retrieve the documents in reverse order, use the sort command as shown in the code below –

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

There are a few other important points worth knowing about capped collections.

  • Documents from a capped collection cannot be deleted.
  • In a capped collection, there are no default indexes present, not even on an id field.
  • MongoDB does not necessarily have to look for a location to accommodate a new document on the disk when inserting a new document. A new document may be blindly added at the tail of a collection. This makes insert operations very quick in capped collections.
  • Similarly, MongoDB returns documents in the same order as the ones present on the disks while reading documents. It makes the reading very quick.

No Sidebar ads