MongoDB ไม่มีคำสั่งคัดลอกคอลเลกชันข้ามฐานข้อมูลโดยตรง ต้องใช้ forEach() ร่วมกับ getSiblingDB() และ insert()
ไวยากรณ์
db.yourCollectionName.find().forEach(function(yourVariableName){
db.getSiblingDB('yourDestinationDatabase')['yourCollectionName'].insert(yourVariableName);
});
ตัวอย่างการใช้งาน
สร้างคอลเลกชันในฐานข้อมูล test:
<test>
> use test
switched to db test
> db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":101,"UserName":"Larry"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c77ad622386c62d05142a67") }
> db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":102,"UserName":"Maxwell"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c77ad6e2386c62d05142a68") }
> db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":103,"UserName":"Robert"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c77ad7c2386c62d05142a69") }
ตรวจสอบฐานข้อมูล sample ก่อนคัดลอก (ยังไม่มีคอลเลกชันนี้):
<sample> > use sample switched to db sample > show collections; deleteDocuments deleteDocumentsDemo deleteInformation employee internalArraySizeDemo sourceCollection updateInformation userInformation
คัดลอกคอลเลกชันจาก 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
ตอนนี้คอลเลกชันปรากฏในทั้งสองฐานข้อมูลแล้ว