- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Clone a collection in MongoDB?
To clone a collection in MongoDB, you can use the forEach() method. Let us first create a collection with a document.
The query to create a collection with a document is as follows −
> 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") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.studentInformation.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8bc15780f10143d8431e21"), "StudentName" : "Chris" } { "_id" : ObjectId("5c8bc15e80f10143d8431e22"), "StudentName" : "Robert" } { "_id" : ObjectId("5c8bc17380f10143d8431e23"), "StudentName" : "James" }
Here is the query to make a clone in MongoDB −
> db.studentInformation.find().forEach( function(copyValue){db.makingStudentInformationClone.insert(copyValue)} );
Let us check the documents of clone collection in MongoDB. The query is as follows −
> db.makingStudentInformationClone.find();
The following is the output −
{ "_id" : ObjectId("5c8bc15780f10143d8431e21"), "StudentName" : "Chris" } { "_id" : ObjectId("5c8bc15e80f10143d8431e22"), "StudentName" : "Robert" } { "_id" : ObjectId("5c8bc17380f10143d8431e23"), "StudentName" : "James" }
Let us now check the list of all collections including clone. The query is as follows −
> show collections;
The following is the output −
copyThisCollectionToSampleDatabaseDemo deleteDocuments deleteDocumentsDemo deleteSomeInformation employee getElementWithMaxIdDemo internalArraySizeDemo makingStudentInformationClone prettyDemo selectWhereInDemo sourceCollection studentInformation updateInformation userInformation
Advertisements