Capped Collections In Mongodb

26 / Jan / 2014 by Sakshi Tyagi 2 comments

We can create collections in mongoDb on which we can apply size limit. These special type of collections are called Capped Collections. These are a kind of circular queues, in which if allocated size limit is reached, it makes space for new documents by overwriting the oldest documents in the collection.

How to create Capped Collections:
db.createCollection(nameOfCollection, {capped: Boolean, autoIndexId: Boolean, size: Number, max : Number})
Here the parameters specify:

  • nameOfCollection: the capped collection name
  • “capped” option : set to true in case to create a capped collection
  • “size” option: specify the size limit for the collection in bytes(mandatory in case of capped collection)
  • “max” option: specify the limit on maximum number of documents allowed in the collection(size option is given preference over max option)
  • “autoIndexId” option: set to false in case of capped collections to disable the automatic index creation

For example lets create a capped collection named “demo”.
create capped collection

Here we have put size limit to 500 bytes and maximum number of documents to 3. Now lets insert some documents in this collection.

Now, the maximum size limit has reached and if we try to add more documents, the old documents get over ridden by new one.

Note: db.collection.isCapped() command is used to check if a collection is a Capped collection or not.

Advantages of Capped Collections:
1. Queries do not need an index to return documents in insertion order due to which it provide higher insertion throughput.

2. Capped collections only allow updates that fit the original document size, which ensures a document does not change its location on disk.

3. Useful for keeping log files.

Disadvantages of Capped Collections:
1. If the update operation increases the original size of the capped collection, the update operation fails.

2. We cannot delete documents from a capped collection. To remove all records from a capped collection, use the { emptycapped: nameOfCollection } command.

3. We cannot shard a capped collection.

So we can make a choice whether to use capped collection according to our use case.

Hope this will help 🙂


comments (2)

  1. Dileep

    There are some restrictions for the role : dbAdmin on running commands such as find(), aggregate() etc. Do you know if there are alternatives for such scenarios in 3.2.x of mongodb?


Leave a Reply

Your email address will not be published. Required fields are marked *