Import-Export commands are very useful, when you are dealing with large application. It is easier to export/import database dump from one server to another.
MongoExport is a command-line tool that produces a JSON or CSV export of data stored in a MongoDB instance.
Note : Run mongoexport from the system command line, not the mongo shell.
MONGOEXPORT
Command to export a collection using host address:
mongoexport --host="<HOSTID>" --username="<USERNAME>" --password="<DBPASSWORD>" --collection="<collection-name>" --db="<db-name>" --out="<filename.json>"After executing above command the specified collection should be exported in current folder.
Note : if the port number is other than default port(27017), then you have specified the port number as well with --port = xxxxx.
Command to export a collection using URI :
mongoexport --uri="mongodb+srv://<USERNAME>:<PASSWORD>@<HOSTNAME>/<DATABASE>" --collection="<COLLECTION>" --type= "<FILETYPE>" --out ="<FILENAME>"
Note : FILETYPE = JSON or CSV
MONGOIMPORT
Command to import json file using host address :
mongoimport --host="<HOSTID>" --username="<USERNAME>" --password="<DBPASSWORD>" --collection="<collection-name>" --db="<db-name>" --file="filename.json"
Command to import json file using URI :
mongoimport --uri="mongodb+srv://<USERNAME>:<PASSWORD>@<HOSTNAME>/<DATABASE> --collection <COLLECTION> --type <FILETYPE> --file <FILENAME>
Some times you may need to export all collection within the DB. For exporting whole database mongodump command should be used.
MONGODUMP
Command to create dump of database using Host ID :
mongodump --host="<HOSTID>" --username="<USERNAME>" --password="<PASSWORD>" --db="<DBNAME>"
After executing above command , a folder called "dump" should be created under the current directory. Inside the dump folder , there will be a folder with db-name.
Command to create dump of database using URI :
mongodump --uri="mongodb+srv://<USERNAME>:<PASSWORD>@<HOSTNAME>/<DATABASE> --username="<USERNAME>" --password="<PASSWORD>"
Or
mongodump --uri "mongodb://<usersname>:<password>@<hostname>/<dbname>?replicaSet=replica_name&authSource=admin" --out “path"
After executing above command , a folder called "dump" should be created under the current directory. Inside the dump folder , there will be a folder with db-name.
To restore collection from dump , you have to use mongorestore command.
Command to restore all collection from dump using Host ID :
mongrestore --host="<HOSTID>" --username="<USERNAME>" --password="<PASSWORD>" --db="<DBNAME>" <DUMP-PATH>
Note : DUMPPATH will be dump/db-name.
Command to restore all collection from dump using URI :
mongorestore --uri="mongodb+srv://<USERNAME>:<PASSWORD>@<HOSTNAME> --username="<USERNAME>" --password="<PASSWORD>" --db="<DBNAME>" <DUMPPATH>
Note : DUMPPATH will be dump/db-name.
Above commands are handy to import export MongoDB database.
Comments
Post a Comment