Export and Import collection from MongoDB

Mercy Jemosop
2 min readNov 12, 2021

--

Import and export collections from mongo DB on linux

Export collection from DB A

A is an example of DB name

open the terminal and type. For clarification on the commands type mongoexport — — help on the terminal

Instance 1.

When the DB is not local and it has credentials. edit all the fields in bold.

sudo mongoexport --host=your_IP --port=port --username=your_username --password=your_pwd --forceTableScan --db your_db --collection  your_collection --type json --out name_of_json.json

Example:

sudo mongoexport --host=182.158.10.1 --port=2987 --username=mercy --password=mercy_pwd --forceTableScan --db UsersDB --collection  Users --type json --out Users.json///to specify your path
/Downloads/Users.json

Instance 2.

When the DB is local and it has no credentials. edit all the fields in bold. You remove the credential if they don’t exist and change Ip to localhost.

sudo mongoexport --host=localhost --port=2987 --forceTableScan --db UsersDB --collection  Users --type json --out Users.json

N.B don’t forget to change the port

To view your document, just check on your present working directory. Type pwd on the terminal.

Import collection from DB A to DB B

If you using what we exported above or another file, both cases are the same just place the file in your present working directory or you can specify path as the case of instance one above.

Instance one with hosted and secured DB

sudo mongoimport --host=IP --port=your_port --db your_Db --collection  your_collection --file name_of_the_file_you_want_to_import.json

Example

sudo mongoimport --host=182.158.10.1 --port=3444 --db SuppliersBD --collection  Users --file Users.json

N.B if it is authenticated add password and username

--username=mercy --password=mercy_pwd

Instance 2.

Importing from a local insecured(if it is secured, add password as above)

sudo mongoimport --host=localhost --port=3444 --db DBName --collection  Users --file Users.json

Hope this helps.

Happy coding!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

--

--

Mercy Jemosop
Mercy Jemosop

Written by Mercy Jemosop

Software Developer. I am open to job referrals. connect with me on twitter @kipyegon_mercy

No responses yet