MongoDB - Constrained Collections

MongoDB - Constrained Collections

Private collections are fixed-size circular collections that follow insertion order to support high performance for create, read, and delete operations. In a circle, this means that when the fixed size allocated to the collection is exhausted, it will start deleting the oldest document in the collection without providing any explicit commands.

Restricted collections restrict updates to documents if the update results in an increase in the size of the document. Because private collections store documents in storage order on disk, this ensures that the size of the document does not increase the amount allocated on disk. Constrained collections are best for storing log information, cache data, or any other large amount of data.

Create a private collection

To create a limited collection, we use the normal createCollection command, but with the capped parameter set to true and specifying the maximum size of the collection in bytes.

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

Apart from the size of the collection, 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 if a collection is capped or not, use the following isCapped command −

> db . cappedLogCollection . isCapped ()

If there is an existing collection that you plan to convert to restricted, you can do so with the following code:

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

This code would convert our existing collection messages to a limited collection.

Requesting a limited collection

By default, a search query for a limited collection will display results in insertion order. But if you want the documents to be received in reverse order, then use the sort command as shown in the following code −

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

There are a few other important things to know about limited collections.

We cannot remove documents from a private collection.

There are no default indexes on a private collection, not even on the _id field.

When you insert a new MongoDB document, you don't actually have to find a place to put the new document on disk. It can blindly insert a new document at the tail of the collection. This makes insert operations on limited collections very fast.

Similarly, when reading documents, MongoDB returns the documents in the same order as they are on disk. This makes the read operation very fast.