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?
Every mongod instance has its own local database, which stores data used in the replication process, and other instance-specific data.
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.
I do this by creating a dump of the remote db to my local machine, which I then restore:
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)
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.)
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)
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 theclon
e commands and their mongo shell helpersdb.copyDatabase()
anddb.cloneDatabase()
.As alternatives, users can use
mongodump
andmongorestore
(with themongorestore
options--nsFrom
and--nsTo
) or write a script using the drivers.
Reference here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With