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
How to copy a collection from one database to another in MongoDB?
In MongoDB, there is no built-in command to copy a collection from one database to another. To achieve this, use the find().forEach() method combined with getSiblingDB() to iterate through documents and insert them into the destination database.
Syntax
db.collectionName.find().forEach(function(doc){
db.getSiblingDB('destinationDatabase')['collectionName'].insert(doc);
});
Create Sample Data
First, let's create a collection in the test database with some documents ?
use test;
db.userCollection.insertMany([
{"User_Id": 101, "UserName": "Larry"},
{"User_Id": 102, "UserName": "Maxwell"},
{"User_Id": 103, "UserName": "Robert"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c77ad622386c62d05142a67"),
ObjectId("5c77ad6e2386c62d05142a68"),
ObjectId("5c77ad7c2386c62d05142a69")
]
}
Verify Source Collection
Display all documents from the source collection ?
db.userCollection.find().pretty();
{
"_id": ObjectId("5c77ad622386c62d05142a67"),
"User_Id": 101,
"UserName": "Larry"
}
{
"_id": ObjectId("5c77ad6e2386c62d05142a68"),
"User_Id": 102,
"UserName": "Maxwell"
}
{
"_id": ObjectId("5c77ad7c2386c62d05142a69"),
"User_Id": 103,
"UserName": "Robert"
}
Copy Collection to Another Database
Now copy the collection from test database to sample database ?
use test;
db.userCollection.find().forEach(function(doc){
db.getSiblingDB('sample')['userCollection'].insert(doc);
});
Verify the Copy Operation
Check if the collection was successfully copied to the sample database ?
use sample; show collections;
userCollection deleteDocuments employee sourceCollection updateInformation
Verify the documents in the copied collection ?
db.userCollection.find();
{
"_id": ObjectId("5c77ad622386c62d05142a67"),
"User_Id": 101,
"UserName": "Larry"
}
{
"_id": ObjectId("5c77ad6e2386c62d05142a68"),
"User_Id": 102,
"UserName": "Maxwell"
}
{
"_id": ObjectId("5c77ad7c2386c62d05142a69"),
"User_Id": 103,
"UserName": "Robert"
}
Key Points
-
getSiblingDB()allows accessing another database without switching context - The original collection remains in the source database − this is a copy operation
- Document
_idvalues are preserved during the copy process
Conclusion
Use find().forEach() with getSiblingDB() to copy collections between databases. This method preserves all document data and structure while keeping the original collection intact in the source database.
