Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

nosql

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

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

like image 268
Luca Martinetti Avatar asked Nov 19 '10 13:11

Luca Martinetti


People also ask

How do I resize a capped collection in MongoDB?

The standard way to resize a capped collection is by creating a new capped collection with the right max size, stop all writing database clients, copy all documents from the old to the new collection, restart database clients and finally delete the old collection.

Which is the data type used by capped collection in MongoDB?

capped: It is used to create a capped collection. If the value of this field is true then you must specify the maximum size in the size field. It is of boolean type.

What is capped collection in MongoDB explain?

What Is a Capped Collection in MongoDB? Fixed-size collections are called capped collections in MongoDB. While creating a collection, the user must specify the collection's maximum size in bytes and the maximum number of documents that it would store.

Which of the following is used for converting a non-capped collection into a capped collection?

The convertToCapped command converts an existing, non-capped collection to a capped collection within the same database.


2 Answers

This is what I do to resize capped collections:

db.runCommand({"convertToCapped": "log", size: 1000000000});

I already have a Capped Collection named "log". So I just run the "convertToCapped" on it again, specifying a new size. I've not tried it on reducing the size of the collection. That may be something that you'd need to use Scott Hernandez's version on. But this works for increasing the size of your capped collections without losing any data or your indexes.


EDIT: @JMichal is correct. Data is preserved, but indexes are not and will need to be recreated.

like image 195
Quixrick Avatar answered Sep 21 '22 01:09

Quixrick


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

like image 45
Scott Hernandez Avatar answered Sep 24 '22 01:09

Scott Hernandez