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
MongoDB - How to copy rows into a newly created collection?
To copy rows from one collection to a newly created collection in MongoDB, use the aggregation pipeline with the $out operator. This operator writes the aggregation results to a specified collection.
Syntax
db.sourceCollection.aggregate([
{ $match: {} },
{ $out: "destinationCollection" }
]);
Sample Data
Let us first create a source collection with employee documents ?
db.sourceCollection.insertMany([
{"EmployeeName": "Robert", "EmployeeSalary": 15000},
{"EmployeeName": "David", "EmployeeSalary": 25000},
{"EmployeeName": "Mike", "EmployeeSalary": 29000}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e0397c1f5e889d7a5199506"),
ObjectId("5e0397c3f5e889d7a5199507"),
ObjectId("5e0397c4f5e889d7a5199508")
]
}
Display the source collection documents ?
db.sourceCollection.find();
{
"_id": ObjectId("5e0397c1f5e889d7a5199506"),
"EmployeeName": "Robert",
"EmployeeSalary": 15000
}
{
"_id": ObjectId("5e0397c3f5e889d7a5199507"),
"EmployeeName": "David",
"EmployeeSalary": 25000
}
{
"_id": ObjectId("5e0397c4f5e889d7a5199508"),
"EmployeeName": "Mike",
"EmployeeSalary": 29000
}
Method 1: Copy All Documents
Copy all documents from sourceCollection to a new destinationCollection ?
db.sourceCollection.aggregate([
{ $out: "destinationCollection" }
]);
Verify the copy operation by displaying the destination collection ?
db.destinationCollection.find();
{
"_id": ObjectId("5e0397c1f5e889d7a5199506"),
"EmployeeName": "Robert",
"EmployeeSalary": 15000
}
{
"_id": ObjectId("5e0397c3f5e889d7a5199507"),
"EmployeeName": "David",
"EmployeeSalary": 25000
}
{
"_id": ObjectId("5e0397c4f5e889d7a5199508"),
"EmployeeName": "Mike",
"EmployeeSalary": 29000
}
Method 2: Copy with Conditions
Copy only employees with salary greater than 20000 ?
db.sourceCollection.aggregate([
{ $match: { "EmployeeSalary": { $gt: 20000 } } },
{ $out: "highSalaryEmployees" }
]);
Key Points
- The
$outoperator creates a new collection or replaces an existing one. - Use
$matchto filter specific documents before copying. - The destination collection will have the same document structure and _id values.
Conclusion
Use MongoDB's aggregation pipeline with the $out operator to copy documents between collections. This method efficiently transfers data while allowing filtering and transformation during the copy process.
