Monday, 31 August 2015

MongoDB Backup and restore (mongodump, mongorestore, mongoexport, mongoimport)

This Post describes the process for creating backups and restoring data using the utilities provided with MongoDB.

The mongorestore and mongodump utilities work with BSON data dumps, and are useful for creating backups of small deployments. For resilient and non-disruptive backups, use a file system or block-level disk snapshot function, such as the methods described in the MongoDB Backup Methods document.

mongodump -d testDB
 
This command will give backup in dump directory (/home/user/dump) here will give your db backup 


mongorestore --host localhost --port 27017 <path_of_database>
 
this command will restore database and then you can check it in to mongo console 
 
 
 
MongoDB’s mongoimport and mongoexport tools allow you to work with your data in a human-readable Extended JSON or CSV format. This is useful for simple ingestion to or from a third-party system, and when you want to backup or export a small subset of your data. For more complex data migration tasks, you may want to write your own import and export scripts using a client driver to interact with the database.
The examples in this section use the MongoDB tools mongoimport and mongoexport. These tools may also be useful for importing data into a MongoDB database from third party applications.
If you want to simply copy a database or collection from one instance to another, consider using the copydb, clone, or cloneCollection commands, which may be more suited to this task. The mongo shell provides the db.copyDatabase() method.
 
 
 
 
When you export in CSV format, you must specify the fields in the documents
to export. The operation specifies the name and address fields
to export.
 
 
mongoexport --db users --collection contacts --type=csv --fields name,address --out /opt/backups/contacts.csv 



Import JSON to Remote Host Running with Authentication

In the following example, mongoimport imports data from the file /opt/backups/mdb1-examplenet.json into the contacts collection within the database marketing on a remote MongoDB database with authentication enabled.
mongoimport connects to the mongod instance running on the host mongodb1.example.net over port 37017. It authenticates with the username user and the password pass.



mongoimport --host mongodb1.example.net --port 37017 --username user --password pass --collection contacts --db marketing --file /opt/backups/mdb1-examplenet.json