How to move a collection from one database to another in MongoDB

In this article, we will see how to move a collection from one database to another in MongoDB. As a maintenance activity its routine task to move a collection from one database to another database in MongoDB Server.

Move a collection from one database to another in MongoDB Syntax:

We must run the below command in admin database only.

db.runCommand({renameCollection: 'db1.source_collection', to: 'db2.target_collection'})

Where
db1.source_collection is the collection to be moved from database db1
db2.target_collection is the collection name in the database db2(target)

Move a collection from one database to another in MongoDB Example:

1. Verify list of the collections from the database ‘r2schools’

use r2schools show collections

2. Now move the collection ‘products’ from database ‘r2schools’ to ‘m201’ database.
We have to switch database to admin. Otherwise it throws error.

use admin db.runCommand({renameCollection: 'r2schools.products', to: 'm201.products'})

Leave a Reply

Your email address will not be published. Required fields are marked *