- Reference >
- Database Commands >
- Administration Commands >
- renameCollection
renameCollection¶
On this page
Definition¶
- renameCollection¶
Changes the name of an existing collection. Specify collection names to renameCollection in the form of a complete namespace (<database>.<collection>).
Issue the renameCollection command against the admin database.
The command takes the following form:
{ renameCollection: "<source_namespace>", to: "<target_namespace>", dropTarget: <true|false> }
The command contains the following fields:
Field Type Description renameCollection string The namespace of the collection to rename. The namespace is a combination of the database name and the name of the collection. to string The new namespace of the collection. If the new namespace specifies a different database, the renameCollection command copies the collection to the new database and drops the source collection. dropTarget boolean Optional. If true, mongod will drop the target of renameCollection prior to renaming the collection. The default value is false.
Behavior¶
renameCollection is suitable for production environments; however:
- renameCollection blocks all database activity for the duration of the operation.
- renameCollection is not compatible with sharded collections.
- renameCollection fails if target is the name of an existing collection and you do not specify dropTarget: true.
Warning
If the renameCollection operation does not complete, the target collection and indexes will not be usable and will require manual intervention to clean up.
Example¶
The following example renames a collection named orders in the test database to orders2014 in the test database.
Warning
This command obtains a global write lock and will block other operations until it has completed.
use admin
db.runCommand( { renameCollection: "test.orders", to: "test.orders2014" } )
The mongo shell provides the db.collection.renameCollection() helper for the command to rename collections within the same database. The following is equivalent to the previous example:
use test
db.orders.renameCollection( "orders2014" )
Exceptions¶
exception 10026: | |
---|---|
Raised if the source namespace does not exist. | |
exception 10027: | |
Raised if the target namespace exists and dropTarget is either false or unspecified. | |
exception 15967: | |
Raised if the target namespace is an invalid collection name. |
Thank you for your feedback!
We're sorry! You can Report a Problem to help us improve this page.