MongoDB Update Collection Name

In MongoDB, you cannot directly rename a collection 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: <boolean>
})

Parameter description:

  • renameCollection: The fully qualified name of the collection to be renamed (including the database name).
  • to: The fully qualified name of the target collection (including the database name).
  • dropTarget(Optional): Boolean value. Whether to delete the target collection if it already exists. The default value isfalse。

Example

Suppose you want to rename oldCollection in the test database to newCollection. You can follow the steps below:

1. Make sure you are connected to the test database

use test

2. 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

  • Permission requirements: ExecuterenameCollectionThe command requires appropriate permissions on the source and target databases. It usually requires thedbAdminordbOwnerrole.

  • The target collection must not exist: The target collection cannot already exist. If the target collection exists, an error will be returned.

  • Indexes and data: Renaming a collection preserves all documents and indexes.

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 results.

Handle Rename Failure

If an error occurs during the rename process, you can take appropriate action based on the error message. For example, if the target collection already exists, you can first delete the target collection (if you confirm it is no longer needed), and then re-run 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 the names of MongoDB collections, ensuring the database structure meets application requirements.

Other Extensions