How can I rename a collection in MongoDB?



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
Updated on: 2019-07-30T22:30:25+05:30

791 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements