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

MongoDBDatabaseBig Data Analytics

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")
}
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9534e816f542d757e2b453")
}
{
"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"),
"UserAge" : 23
}
{
"_id" : ObjectId("5c9534e816f542d757e2b453"),
"UserAge" : 26
}
{
"_id" : ObjectId("5c9534f116f542d757e2b454"),
"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"),
"UserAge" : 23
}
{
"_id" : ObjectId("5c9534e816f542d757e2b453"),
"UserAge" : 26
}
{
"_id" : ObjectId("5c9534f116f542d757e2b454"),
"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
userInformation