要在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()method的帮助下显示集合中的所有文档。查询如下-
> 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