How can I rename a collection in MongoDB?

MongoDBDatabaseBig Data Analytics

To rename a collection in MongoDB, you can use renameCollection() method. The syntax is as follows −

db.yourOldCollectionName.renameCollection('yourNewCollectionName');

To understand the above syntax, let us list all the collections from database sample. The query is as follows −

> use sample;
switched to db sample
> show collections;

The following is the output −

copyThisCollectionToSampleDatabaseDemo
deleteDocuments
deleteDocumentsDemo
employee
informationAboutDelete
internalArraySizeDemo
prettyDemo
selectWhereInDemo
sourceCollection
updateInformation
userInformation

Now change collection name ‘informationAboutDelete’ to ‘deleteSomeInformation’. The query is as follows to change the collection name.

> db.informationAboutDelete.renameCollection('deleteSomeInformation');
{ "ok" : 1 }

Here is the query to check the collection name has been renamed to 'deleteSomeInformation' −

> show collections;

The following is the output −

copyThisCollectionToSampleDatabaseDemo
deleteDocuments
deleteDocumentsDemo
deleteSomeInformation
employee
internalArraySizeDemo
prettyDemo
selectWhereInDemo
sourceCollection
updateInformation
userInformation
raja
Published on 29-Mar-2019 15:55:16
Advertisements