Merging collections in mongodb

Posted on August 17, 2011


I recently renamed a Rails model which was a Mongoid::Document. Since there was no explicit store_in set in the model, mongodb would store all new documents in the collection corresponding to the new model name. So I ended up with two collections for the same kind of document.

I added the store_in :target_collection to the model to fix the issue for all new documents.

Now I still needed to merg the accidentally created collection in the main one. After some googling and this Stackoverflow article I did the following procedure:

1. call the mongodb console from the command line


2. Get a list of databases on the localhost

> show dbs

3. Select the database

use my_main_data_base

4. Check the existing collections

show collections

5. Optional: check the size of the collections


6. Do the actual merge. Since there is no bulk insert into mongodb, we loop all objects in the source_collection and insert them one by one into the target_collection:





Posted in: Uncategorized