In MongoDB, the command does not exist to copy a collection from one database to another. To achieve it, use the below concept −
db.yourCollectionName.find().forEach(function(yourVariableName){ db.getSiblingDB('yourDestinationDatabase')['yourCollectionName'].insert(yourVariableName); });
Let us create a collection in the test database and copy this collection to another database with the name „sample‟.
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
<test>
> use test switched to db test > db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":101,"UserName":"Larr y"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77ad622386c62d05142a67") } > db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":102,"UserName":"Maxwell"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77ad6e2386c62d05142a68") } > db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":103,"UserName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77ad7c2386c62d05142a69") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.copyThisCollectionToSampleDatabaseDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c77ad622386c62d05142a67"), "User_Id" : 101, "UserName" : "Larry" } { "_id" : ObjectId("5c77ad6e2386c62d05142a68"), "User_Id" : 102, "UserName" : "Maxwell" } { "_id" : ObjectId("5c77ad7c2386c62d05142a69"), "User_Id" : 103, "UserName" : "Robert" }
Let us check the sample database has a collection with the name “copyThisCollectionToSampleDatabaseDemo” or not.
The query is as follows −
<sample>
> use sample; switched to db sample > show collections;
The following is the output −
deleteDocuments deleteDocumentsDemo deleteInformation employee internalArraySizeDemo sourceCollection updateInformation userInformation
So, there is no collection with name “copyThisCollectionToSampleDatabaseDemo”.
Now we will copy the above collection from a test database to sample database. The query is as follows −
> use test; switched to db test > db.copyThisCollectionToSampleDatabaseDemo.find().forEach(function(send){ db.getSiblingDB('sample')['copyThisCollectionToSampleDatabaseDemo'].insert(send); });
Now let us check once again the collection is copied or not successfully in the sample database.
The query is as follows −
> use sample; switched to db sample > show collections;
The following is the output −
copyThisCollectionToSampleDatabaseDemo deleteDocuments deleteDocumentsDemo deleteInformation employee internalArraySizeDemo sourceCollection updateInformation userInformation
Look at the sample output, the collection “copyThisCollectionToSampleDatabaseDemo” is present in the sample database while it is present in the test database also.