MongoDB में एक डेटाबेस से दूसरे में कलेक्शन कॉपी करने के लिए डायरेक्ट कमांड नहीं है। forEach() और getSiblingDB() का उपयोग करके इसे प्राप्त करें।
सिंटैक्स
db.yourCollectionName.find().forEach(function(yourVariableName) {
db.getSiblingDB('yourDestinationDatabase')['yourCollectionName'].insert(yourVariableName);
});
उदाहरण से समझें
सोर्स डेटाबेस (test) में कलेक्शन बनाएं:
> use test
switched to db test
> db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id": 101, "UserName": "Larry"});
> db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id": 102, "UserName": "Maxwell"});
> db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id": 103, "UserName": "Robert"});
डेस्टिनेशन डेटाबेस (sample) चेक करें:
> use sample switched to db sample > show collections;
आउटपुट (कॉपी से पहले):
deleteDocuments deleteDocumentsDemo deleteInformation employee internalArraySizeDemo sourceCollection updateInformation userInformation
कलेक्शन copyThisCollectionToSampleDatabaseDemo मौजूद नहीं है।
अब test से sample में कॉपी करें:
> use test
switched to db test
> db.copyThisCollectionToSampleDatabaseDemo.find().forEach(function(send) {
db.getSiblingDB('sample')['copyThisCollectionToSampleDatabaseDemo'].insert(send);
});
फिर से sample डेटाबेस चेक करें:
> use sample switched to db sample > show collections;
आउटपुट (कॉपी के बाद):
copyThisCollectionToSampleDatabaseDemo deleteDocuments deleteDocumentsDemo deleteInformation employee internalArraySizeDemo sourceCollection updateInformation userInformation
कलेक्शन सफलतापूर्वक कॉपी हो गया। नोट: बड़े डेटासेट के लिए mongodump/mongorestore अधिक कुशल है।