Using Capped Collections

A great feature of MongoDB is the ability to create a capped collection. A capped collection is a collection that has a fixed size. When a new document needs to be written to a collection that exceeds the size of the collection, the oldest document in the collection is deleted, and the new document is inserted. Capped collections work great for objects that have a high rate of insertion, retrieval, and deletion.

The following are the benefits of using capped collections:

Image They guarantee that the insert order is preserved. Thus queries do not need to utilize an index to return documents in the order in which they were stored, eliminating the indexing overhead.

Image They also guarantee that the insertion order is identical to the order on disk by prohibiting updates that increase the document size. This eliminates the overhead of relocating and managing the new location of documents.

Image They automatically remove the oldest documents in the collection. Therefore, you do not need to implement deletion in your application code.

You need to be careful using capped collections, though, because they are subject to the following restrictions:

Image Documents cannot be updated to a larger size once they have been inserted into a capped collection. You can update them, but the data must be the same size or smaller.

Image Documents cannot be deleted from a capped collection. This means the data takes up space on disk even if it is not being used. You can explicitly drop a capped collection to effectively delete all entries, but you will then need to re-create it in order to use it again.

A great use of capped collections is as a rolling log of transactions in your system. You can always access the last X number of log entries without needing to explicitly clean up the oldest.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.19.220