如何克隆 MongoDB 中的集合?


要在 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

更新於: 2019 年 7 月 30 日

594 次瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.