Thursday, July 11, 2013

How to Import and Export MongoDB Databases

It’s been a few wonderful weeks of working with MongoDB. Just like in MySQL i’ve already come to a point where i need to play around with db dumps and i looked up online on how to perform mysqldump for mongodb?


It’s always exciting to know that a platform got a solution to your problem, as i came around the mongodump. FYI - looking online i came across many different ways to perform the importing/exporting mongodb databases, and there is some excellent documentation on the mongodb.org site about the various tools.
I moved around my data, and the steps were so straightforward so I thought I'd write down the commands that I used so I can refer to them later, just as i'm doing on all other posts.
Part 1: Exporting from MongoDB
To perform this export of my database, i did simply tell mongodump which database (known as  collection in Mongo :) wonder why? )  to export. So my database is called “refugees”. Note that the mongodump command is a command-line utility and is supposed to be tun from the system command prompt and not the mongodb shell.

mongodump --db refugees --collection stats
This dumps the refugees database into the dump directory. Feel free to leave out the --collection part if you want to export the whole database. 

This is what we have in that directory dump:
refugees
├── stats.bson
└── system.indexes.bson

0 directories, 2 files
So that means that the only collection in my refugees database is the stats collection. You will also notice a  .bson file for each collection in the database, in addition i’ve also noticed that  there is a system indexes collection.
Part 2: How to drop a Mongodb Database (command-line).
What about if you already got another db running and wanted to first drop it then you should run this on the mongo Shell. Don't forget i'm using my db called 'refugees'

> use refugees; 
> db.dropDatabase();

Or run this on the command prompt. 
mongo refugees --eval "db.dropDatabase()"


Part 3: How to import  to MongoDB
Next problem was now i got this data dump, how can i import it to my new server, i simply use the mongorestore command, which accepts either a single .bson file representing a collection, or a directory containing multiple files. I also just found this later online - Here's my example:
mongorestore -d refugees /the/path/that/i/too/to/refugees/directory

I’ve  also noticed that one can specify any database name and path to files that they like. I know i’ll need this again at some point and backing these steps up on my blog :) hoping i find someone else to help too.

No comments:

Post a Comment

Add any comments if it helped :)