Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธี Clone Collection ใน MongoDB

Clone Collection ด้วย forEach() และ insert()

ใช้ Method forEach() วนลูปผ่าน Document ทุกตัว แล้ว Insert เข้า Collection ใหม่

สร้าง Collection ต้นทาง

> 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") }

Clone ไปยัง Collection ใหม่

> db.studentInformation.find().forEach( function(copyValue){ db.makingStudentInformationClone.insert(copyValue) } );

ตรวจสอบ Collection ใหม่

> db.makingStudentInformationClone.find();
{ "_id" : ObjectId("5c8bc15780f10143d8431e21"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c8bc15e80f10143d8431e22"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c8bc17380f10143d8431e23"), "StudentName" : "James" }

รายการ Collections ทั้งหมด

> show collections;
copyThisCollectionToSampleDatabaseDemo deleteDocuments deleteDocumentsDemo deleteSomeInformation employee getElementWithMaxIdDemo internalArraySizeDemo makingStudentInformationClone prettyDemo selectWhereInDemo sourceCollection studentInformation updateInformation userInformation

Collection makingStudentInformationClone ถูกสร้างขึ้นมาแล้ว พร้อมข้อมูลเหมือนต้นทาง