如何克隆 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