How do I insert a record from one Mongo database into another?


You can switch from one database to another using the use command. Here, we are using the collection in the “test” database. Let us insert that collection in another database with the name “sample”.

To understand further, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.insertOneRecordDemo.insertOne({"UserName":"Larry","UserAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9534de16f542d757e2b452")
}
> db.insertOneRecordDemo.insertOne({"UserName":"Chris","UserAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9534e816f542d757e2b453")
}
> db.insertOneRecordDemo.insertOne({"UserName":"David","UserAge":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9534f116f542d757e2b454")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c9534de16f542d757e2b452"),
   "UserName" : "Larry",
   "UserAge" : 23
}
{
   "_id" : ObjectId("5c9534e816f542d757e2b453"),
   "UserName" : "Chris",
   "UserAge" : 26
}
{
   "_id" : ObjectId("5c9534f116f542d757e2b454"),
   "UserName" : "David",
   "UserAge" : 25
}

Here is the query to insert a record from one MongoDB database into another −

> var AllDocumentsFromSourceCollection = db.insertOneRecordDemo.find();
> use sample;
switched to db sample
> AllDocumentsFromSourceCollection.forEach(function(allRecords){ db.getAllRecordsFromSourceCollectionDemo.insert(allRecords) });

Check the record has been inserted or not. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c9534de16f542d757e2b452"),
   "UserName" : "Larry",
   "UserAge" : 23
}
{
   "_id" : ObjectId("5c9534e816f542d757e2b453"),
   "UserName" : "Chris",
   "UserAge" : 26
}
{
   "_id" : ObjectId("5c9534f116f542d757e2b454"),
   "UserName" : "David",
   "UserAge" : 25
}

Now you can check the collection name is present or not in the sample database. The query is as follows −

> show collections;

The following is the output −

arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
truncateDemo
updateInformation
userInformation

Updated on: 30-Jul-2019

396 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements