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:
- renameCollection: the fully qualified name of the collection to rename (including the database name).
- to: the fully qualified name of the target collection (including the database name).
- dropTarget(optional): a boolean value. Whether to drop the target collection if it already exists. The default value is
false。
Example
Suppose you want to rename oldCollection in the test database to newCollection, you can proceed as follows:
- Make sure you are connected to the test database
use test
- 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: Before executing
renameCollectionThe command requires appropriate permissions on both the source and target databases. Usually thedbAdminordbOwnerrole is required. -
Target collection does not exist: the target collection must not 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 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.