Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Clone a collection in MongoDB?
To clone a collection in MongoDB, use the forEach() method to iterate through documents and insert them into a new collection. This creates an exact copy with all documents and their _id values preserved.
Syntax
db.sourceCollection.find().forEach(function(doc) {
db.targetCollection.insert(doc);
});
Sample Data
First, let's create a collection with sample documents ?
db.studentInformation.insertMany([
{"StudentName": "Chris"},
{"StudentName": "Robert"},
{"StudentName": "James"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8bc15780f10143d8431e21"),
ObjectId("5c8bc15e80f10143d8431e22"),
ObjectId("5c8bc17380f10143d8431e23")
]
}
Display the original collection ?
db.studentInformation.find();
{ "_id": ObjectId("5c8bc15780f10143d8431e21"), "StudentName": "Chris" }
{ "_id": ObjectId("5c8bc15e80f10143d8431e22"), "StudentName": "Robert" }
{ "_id": ObjectId("5c8bc17380f10143d8431e23"), "StudentName": "James" }
Clone the Collection
Use forEach() to clone all documents to a new collection ?
db.studentInformation.find().forEach(function(doc) {
db.studentInformationClone.insert(doc);
});
Verify the Clone
Check that the cloned collection contains identical documents ?
db.studentInformationClone.find();
{ "_id": ObjectId("5c8bc15780f10143d8431e21"), "StudentName": "Chris" }
{ "_id": ObjectId("5c8bc15e80f10143d8431e22"), "StudentName": "Robert" }
{ "_id": ObjectId("5c8bc17380f10143d8431e23"), "StudentName": "James" }
Verify both collections exist ?
show collections;
studentInformation studentInformationClone
Key Points
- The
forEach()method preserves original_idvalues in the cloned collection. - Both collections will contain identical documents with the same ObjectIds.
- The target collection is created automatically if it doesn't exist.
Conclusion
Use find().forEach() with insert() to create an exact clone of a MongoDB collection. This method preserves all document fields and ObjectIds, creating a perfect duplicate collection.
Advertisements
