如何克隆 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP