Search code examples
pythonmongodbmongo-collection

How to merge two databases of mongoDB present in two different computers?


I am using mongoDB to store the data of a particular website. Since two of us are working, we are using our own computer for the job. Both the computer has a database website_data and a collection in that database webpages. Now for some analysis, and to plot graphs, I need the whole data in a single pc. How to combine the two databases? I thought of writing a script but I don't know how to connect to the other computer's database. Is there some database file which I can copy directly onto my pc?


Solution

  • You can do this with the command line tools mongodump and mongorestore.

    Use mongodump --db [dbname] on the source computer to export all collections of the database into files which are stored in the directory dump/[collection].bson. Copy the files to the target computer and then use mongorestore --db [dbname] [collection].bson to import the generated files into the consolidated database. The contents will be appended to the existing collections as if you would use the insert command.

    When you want to do it like a senior sysadmin: both command line tools have command line options to perform said operations on a remote system and you can pipe the output of mongodump right into mongorestore, so when you want to show off you could do it with one console command from a remote system. But when this is a one time thing and command line trickery is not your passion, rather stick to files.