Home >>MongoDB Tutorial >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.
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.
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.