ในการโคลนคอลเลกชันใน MongoDB คุณสามารถใช้เมธอด forEach() ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน
แบบสอบถามเพื่อสร้างคอลเลกชันที่มีเอกสารมีดังนี้ -
> db.studentInformation.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8bc15780f10143d8431e21")
}
> db.studentInformation.insertOne({"StudentName":"Robert"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8bc15e80f10143d8431e22")
}
> db.studentInformation.insertOne({"StudentName":"James"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8bc17380f10143d8431e23")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้เมธอด find() แบบสอบถามมีดังนี้ −
> db.studentInformation.find().pretty();
ต่อไปนี้เป็นผลลัพธ์ -
{ "_id" : ObjectId("5c8bc15780f10143d8431e21"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c8bc15e80f10143d8431e22"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c8bc17380f10143d8431e23"), "StudentName" : "James" } นี่คือแบบสอบถามเพื่อสร้างโคลนใน MongoDB -
> db.studentInformation.find().forEach( function(copyValue){db.makingStudentInformationClone.insert(copyValue)} ); ให้เราตรวจสอบเอกสารของการรวบรวมโคลนใน MongoDB แบบสอบถามมีดังนี้ −
> db.makingStudentInformationClone.find();
ต่อไปนี้เป็นผลลัพธ์ -
{ "_id" : ObjectId("5c8bc15780f10143d8431e21"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c8bc15e80f10143d8431e22"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c8bc17380f10143d8431e23"), "StudentName" : "James" } ให้เราตรวจสอบรายการของคอลเลกชันทั้งหมดรวมทั้งโคลน แบบสอบถามมีดังนี้ −
> show collections;
ต่อไปนี้เป็นผลลัพธ์ -
copyThisCollectionToSampleDatabaseDemo deleteDocuments deleteDocumentsDemo deleteSomeInformation employee getElementWithMaxIdDemo internalArraySizeDemo makingStudentInformationClone prettyDemo selectWhereInDemo sourceCollection studentInformation updateInformation userInformation