Convert whole collection to one db to new dbs

Can you please help me, I am trying to copy all collections in a specific database to create a new database and move it to it. But the following code doesn't work. and my team name in db contains two parts "mg2.data", "mg32.data". I want to create a new database mg2 and copy collection name as data. collection name mg2.data must be in the mg2 database and collection name data.

db.getCollectionNames().forEach(function( a ){
if(a!='system.indexes' ) {
var sp = a.split('.');
var dbName = sp[0];
var col = sp[1];
//print(dbName)

db[a].copyTo(db.getSiblingDB(dbName).getcCollection(col));

}
});

      

Here are the details of my situation.

I have the name Db Master and it contains about 60-70 collections of its names like (mg1.data, mg2.data, mg3.data) and I want it to be similar db name mg1 and collection name data db name mg2 and data about the collection name, etc. I faced the problem that when in the first project the write operation locks the whole database (Master). I can't go to the shards and that's it now.

+3


source to share


1 answer


This approach works for me. I don't know this is the best aproach



db.getCollectionNames().forEach(function( a ){
if(a!='system.indexes' ) {
var sp = a.split('.');
var dbName = sp[0];
var col = sp[1];
print(dbName+'\n');

//db[a].copyTo(db.getSiblingDB(dbName).getcCollection(col));
db[a].find().forEach(function(d){ db.getSiblingDB(dbName)[col].insert(d); });

}
});

      

+3


source







All Articles