- Reference >
- Database Commands >
- renameCollection
renameCollection¶
-
renameCollection¶ The
renameCollectioncommand is an administrative command that changes the name of an existing collection. You specify collections torenameCollectionin the form of a complete namespace, which includes the database name. To rename a collection, issue therenameCollectioncommand against the admin database in the form:The
dropTargetargument is optional.If you specify a collection to the
toargument in a different database, therenameCollectioncommand will copy the collection to the new database and then drop the source collection.Parameters: - source-namespace – Specifies the complete namespace of the collection to rename.
- to (string) – Specifies the new namespace of the collection.
- dropTarget (boolean) – Optional. If
true,mongodwill drop thetargetofrenameCollectionprior to renaming the collection.
Exception: - 10026 – Raised if the
sourcenamespace does not exist. - 10027 – Raised if the
targetnamespace exists anddropTargetis eitherfalseor unspecified. - 15967 – Raised if the
targetnamespace is an invalid collection name.
You can use
renameCollectionin production environments; however:renameCollectionwill block all database activity for the duration of the operation.renameCollectionis incompatible with sharded collections.
Warning
renameCollectionwill fail if target is the name of an existing collection and you do not specifydropTarget: true.If the
renameCollectionoperation does not complete thetargetcollection and indexes will not be usable and will require manual intervention to clean up.The shell helper
db.collection.renameCollection()provides a simpler interface to using this command within a database. The following is equivalent to the previous example:Warning
You cannot use
renameCollectionwith sharded collections.Warning
This command obtains a global write lock and will block other operations until it has completed.