Capped collections are fixed-size circular collections that comply with the insertion order to help high overall performance for create, examine, and delete operations. By circular, it method that once the constant length allotted to the gathering is exhausted, it's going to start deleting the oldest record in the series with out supplying any specific commands.
Capped collections restriction updates to the files if the replace effects in extended document size. Since capped collections save files in the order of the disk garage, it guarantees that the document length does no longer boom the dimensions allocated at the disk. Capped collections are quality for storing log statistics, cache information, or every other excessive volume facts.
Creating Capped Collection
To create a capped series, we use the everyday createCollection command however with capped alternative as actual and specifying the most length of series in bytes.
>db.createCollection("cappedLogCollection",{capped:true,size:10000})
In addition to collection size, we also can limit the wide variety of files inside the collection the usage of the max parameter −
>db.createCollection("cappedLogCollection",{capped:true,size:10000,max:1000})
If you need to test whether a collection is capped or now not, use the subsequent isCapped command −
>db.cappedLogCollection.isCapped()
If there may be an current series which you are making plans to transform to capped, you can do it with the subsequent code −
>db.runCommand({"convertToCapped":"posts",size:10000})
This code could convert our present series posts to a capped series.
Querying Capped Collection
By default, a discover query on a capped collection will display effects in insertion order. But if you want the files to be retrieved in reverse order, use the type command as shown in the following code −
>db.cappedLogCollection.find().sort({$natural:-1})
There are few other crucial points regarding capped collections well worth knowing −
- We can not delete documents from a capped series.
- There are no default indexes present in a capped series, not even on _id field.
- While putting a new document, MongoDB does now not have to clearly look for an area to deal with new document on the disk. It can blindly insert the brand new file at the tail of the gathering. This makes insert operations in capped collections very fast.
- Similarly, whilst studying documents MongoDB returns the documents inside the identical order as present on disk. This makes the read operation very rapid.