Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MongoDB Rename Collection

MongoDB Rename Collection

In MongoDB, you cannot rename a collection directly through a command.

MongoDB can use the renameCollection method to rename a collection.

The renameCollection method runs in MongoDB's admin database and can rename a collection to another name.

The syntax of the renameCollection command:

db.adminCommand({

  renameCollection: "sourceDb.sourceCollection",

  to: "targetDb.targetCollection",

  dropTarget: 

})

Parameter Description:

Example

Suppose you want to rename oldCollection in the test database to newCollection, you can proceed as follows:

  1. Make sure you are connected to the test database


use test

  1. Run the renameCollection command


db.adminCommand({ 

  renameCollection: "test.oldCollection", 

  to: "test.newCollection" 

});

If you want to rename a collection to another database, for example, rename oldCollection in the test database to newCollection in the production database, you can do this:

db.adminCommand({ 

  renameCollection: "test.oldCollection", 

  to: "production.newCollection" 

});

Notes

Check the rename result

After renaming, you can check whether the new collection exists with the following command:



use test

show collections

If the collection has been renamed to newCollection, you should see newCollection in the result.

Handling rename failures

If an error occurs during renaming, you can take appropriate measures based on the error message. For example, if the target collection already exists, you can first drop the target collection (if you confirm it is not needed), and then re-execute the rename operation:

Example

use production

db.

newCollection

.

drop

(

)

;

use test

db.

adminCommand

(

{

  renameCollection

:

"test.oldCollection"

,

  to

:

"production.newCollection"

}

)

;

Through the renameCollection method, you can effectively manage MongoDB collection names and ensure the database structure meets application requirements.