Mongodb migration and appending data to existing database

backupmigrationmongodbnosqlrestore

I have two databases in two different machines containing data in same schema. Both have relational mappings in form of ObjectIDs as it is done in NoSQL database. The task at hand is to pick one database from machine A and append that data to another database residing in the machine B. If I simply insert the data there will be ObjectID collisions and it simply won't work.
The only option which I see is to insert the primary key collections first in the database, then insert the collections containing the foreign key mappings and replace the ObjectIDs with the newly created ObjectIDs from the primary key documents. However, it isn't as easy as it sounds because there are multiple collections which are interconnected with ObjectIDs.

Please suggest me the most efficient way in which this can be done. TIA

Best Answer

In mongoshell you can connect to several databases and use them at the same time. A plain simple copy would be this one:

var db_A = Mongo("mongodb://user:password@host-A").getDB("data")
var db_B = Mongo("mongodb://user:password@host-B").getDB("data")

var docs = db_A.getCollection("collection_name").find().toArray();
if (docs.length > 0) {
    db_B.getCollection("collection_name").insertMany(docs, {ordered: false});
}

Your migration script will look more complex of course, but that's the way you can do it.