Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying MongoDB Database into Local Machine

I have a MongoDB database that resides on a remote server machine whose IP address is 192.168.1.20 on a local network. For development and testing purposes, and since I am not allowed to modify or delete the database on the server for security purposes, I want to copy the database on my local machine for my personal use.

Can anyone please tell me, how do I achieve this?

like image 786
Razor Avatar asked Jan 03 '14 10:01

Razor


People also ask

Can MongoDB be stored locally?

Every mongod instance has its own local database, which stores data used in the replication process, and other instance-specific data.

How do I export an entire MongoDB database?

So, to export data from the MongoDB database, MongoDB provides a command-line tool known as mongoexport. Using this tool you can exports data of a collection in JSON or CSV(comma-separated value) format. Moreover, we can also use features like limit and sort on a collection while exporting the data.


2 Answers

I do this by creating a dump of the remote db to my local machine, which I then restore:

  1. Make sure you have a mongo instance up and running (eg. run mongod.exe from your bin folder in a terminal window. On my windows computer that's C:\mongodb\bin)

  2. Make a dump from remote db: Open a new terminal window, move to the bin folder again, run:

    mongodump -h example.host.com --port 21018 -d dbname --username username --password yourpass

    (Change the parameters to suit your own situation.)

  3. Restore the dumped database: Once the dump has been made, run the following command so that you have a local db:

    mongorestore -d theNameYouWantForYourLocalDB dump\nameOfRemoteDB

    (replace nameOfRemoteDB with the name of the remote db, the same as in previous command, and replace theNameYouWantForYourLocalDB with the name that you want your new local db to have)

like image 197
malla Avatar answered Oct 19 '22 23:10

malla


There is copy database command which I guess should be good fit for your need.

db.copyDatabase("DATABASENAME", "DATABASENAME", "localhost:27018");

Alternatively, you can just stop MongoDb, copy the database files to another server and run an instance of MongoDb there.


EDIT 2020-04-25

Quote from MongoDB documentation

MongoDB 4.0 deprecates the copydb and the clone commands and their mongo shell helpers db.copyDatabase() and db.cloneDatabase().

As alternatives, users can use mongodump and mongorestore (with the mongorestore options --nsFrom and --nsTo) or write a script using the drivers.

Reference here

like image 28
sas Avatar answered Oct 19 '22 23:10

sas