MongoDB - How to copy rows into a newly created collection?


To copy rows into another collection, use MongoDB. The syntax is as follows wherein “yourOldCollectionName” is the old collection, whereas where this collection will get copied is our new collection i.e. “yourNewCollectionName” −

db.yourOldCollectionName.aggregate([{ $sample: { size: 333333 }}, {$out: "yourNewCollectionName"} ],{allowDiskUse: true});

Let us first create a collection with documents −

> db.sourceCollection.insertOne({"EmployeeName":"Robert","EmployeeSalary":15000});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0397c1f5e889d7a5199506")
}
> db.sourceCollection.insertOne({"EmployeeName":"David","EmployeeSalary":25000});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0397c3f5e889d7a5199507")
}
> db.sourceCollection.insertOne({"EmployeeName":"Mike","EmployeeSalary":29000});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0397c4f5e889d7a5199508")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.sourceCollection.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e0397c1f5e889d7a5199506"),
   "EmployeeName" : "Robert",
   "EmployeeSalary" : 15000
}
{
   "_id" : ObjectId("5e0397c3f5e889d7a5199507"),
   "EmployeeName" : "David",
   "EmployeeSalary" : 25000
}
{
   EmployeeName" : "Mike",
   "E"_id" : ObjectId("5e0397c4f5e889d7a5199508"),
   "mployeeSalary" : 29000
}

Here is the query to create a new collection “destinationCollection” −

> db.createCollection('destinationCollection');
{ "ok" : 1 }

Following is the query to copy rows from “sourceCollection” to another new collection “destinationCollection” −

> db.sourceCollection.aggregate([{ $sample: { size: 333333 }}, {$out: "destinationCollection"} ],{allowDiskUse: true});

Following is the query to display all documents from a collection with the help of find() method −

> db.destinationCollection.find().pretty()

This will produce the following output wherein the new collection copied records from 1st collection “sourceCollection” −

{
   "_id" : ObjectId("5e0397c4f5e889d7a5199508"),
   "EmployeeName" : "Mike",
   "EmployeeSalary" : 29000
}
{
   "_id" : ObjectId("5e0397c3f5e889d7a5199507"),
   "EmployeeName" : "David",
   "EmployeeSalary" : 25000
}
{
   "_id" : ObjectId("5e0397c1f5e889d7a5199506"),
   "EmployeeName" : "Robert",
   "EmployeeSalary" : 15000
}

Updated on: 27-Mar-2020

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements