Search code examples
mongodbnosql

How can I resize a mongodb capped collection without losing data?


How can I resize a mongodb capped collection without losing data?

Is there a command for that, or could somebody provide a script?


Solution

  • You basically need to create a new capped collection and copy the docs to it. This can be done very easily in the javascript (shell), or your language of choice.

    db.createCollection("new", {capped:true, size:1073741824}); /* size in bytes */
    db.old.find().forEach(function (d) {db.new.insert(d)});
    db.old.renameCollection("bak", true);
    db.new.renameCollection("old", true);
    

    Note: Just make sure nobody is inserting/updating the old collection when you switch. If you run that code in a db.eval("....") it will lock the server while it runs.

    There is a feature request for increasing the size of an existing collection: http://jira.mongodb.org/browse/SERVER-1864