Random thoughts of a warped mind…

December 2, 2011

Extending a capped collection on Mongodb

Filed under: All,Databases,Mongo — Srinivas @ 11:50

A capped collection in MongoDB is a FIFO of a fixed size. At the time of creating the collection, you specify a fixed size and Mongo maintains this table at that size – FIFO in the sense that the oldest documents are rolled out of the collection to make way for the new inserts. This means no need to manually cleanout the table.

However once a capped collection is created, there is no option to resize it (Say you initially created a 512MB collection that you now want to extend to 1GB…). And neither can you delete documents from a capped collection. The alternative is to create a new capped collection, copy in the rows from the original collection into it and rename the collections.

Assuming you have existing capped collection “orig” that you want to resize, here is what you would do(If you are’nt sure if the collection is capped, you can always run db.orig.isCapped() to find out if it is – a return value of True means it is capped).

<br />db.createCollection("temptable", {capped:true, size:1073741824});//Capped coll of 1GB<br />db.orig.find().forEach(function (d) {db.temptable.insert(d)});<br />db.orig.renameCollection("old_orig", true);<br />db.temptable.renameCollection("orig", true);<br />

Then optionally drop the “old_orig” collection via db.old_orig.drop(). You want to make sure that while you are doing this, you don’t have your apps inserting into this collection!

Powered by WordPress