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
How do I insert a record from one Mongo database into another?
To insert records from one MongoDB database into another, use the find() method to retrieve documents from the source collection, then iterate through them with forEach() to insert into the destination database.
Syntax
var documents = db.sourceCollection.find();
use targetDatabase;
documents.forEach(function(doc) {
db.targetCollection.insertOne(doc);
});
Sample Data
Let's create a collection in the "test" database with some sample documents:
db.insertOneRecordDemo.insertMany([
{"UserName": "Larry", "UserAge": 23},
{"UserName": "Chris", "UserAge": 26},
{"UserName": "David", "UserAge": 25}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9534de16f542d757e2b452"),
ObjectId("5c9534e816f542d757e2b453"),
ObjectId("5c9534f116f542d757e2b454")
]
}
Method 1: Copy All Documents
First, verify the source data:
db.insertOneRecordDemo.find().pretty();
{
"_id": ObjectId("5c9534de16f542d757e2b452"),
"UserName": "Larry",
"UserAge": 23
}
{
"_id": ObjectId("5c9534e816f542d757e2b453"),
"UserName": "Chris",
"UserAge": 26
}
{
"_id": ObjectId("5c9534f116f542d757e2b454"),
"UserName": "David",
"UserAge": 25
}
Now copy all documents to the "sample" database:
var AllDocumentsFromSourceCollection = db.insertOneRecordDemo.find();
use sample;
AllDocumentsFromSourceCollection.forEach(function(allRecords){
db.getAllRecordsFromSourceCollectionDemo.insertOne(allRecords);
});
Verify Results
Check if records were successfully inserted in the target database:
db.getAllRecordsFromSourceCollectionDemo.find().pretty();
{
"_id": ObjectId("5c9534de16f542d757e2b452"),
"UserName": "Larry",
"UserAge": 23
}
{
"_id": ObjectId("5c9534e816f542d757e2b453"),
"UserName": "Chris",
"UserAge": 26
}
{
"_id": ObjectId("5c9534f116f542d757e2b454"),
"UserName": "David",
"UserAge": 25
}
Verify the collection exists in the target database:
show collections;
getAllRecordsFromSourceCollectionDemo
Key Points
- Use
find()to retrieve all documents from the source collection -
forEach()iterates through each document for insertion - Original
_idvalues are preserved during the copy process - Use
use databaseNameto switch between databases
Conclusion
The forEach() method combined with find() provides a simple way to copy documents between MongoDB databases. This approach preserves document structure and IDs while transferring data to the target collection.
Advertisements
