renameCollection

renameCollection

The renameCollection command is an administrative command that changes the name of an existing collection. You specify collections to renameCollection in the form of a complete namespace, which includes the database name. To rename a collection, issue the renameCollection command against the admin database in the form:

{ renameCollection: <source-namespace>, to: <target-namespace>[, dropTarget: <boolean> ] }

The dropTarget argument is optional.

If you specify a collection to the to argument in a different database, the renameCollection command 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, mongod will drop the target of renameCollection prior to renaming the collection.
Exception:
  • 10026 – Raised if the source namespace does not exist.
  • 10027 – Raised if the target namespace exists and dropTarget is either false or unspecified.
  • 15967 – Raised if the target namespace is an invalid collection name.

You can use renameCollection in production environments; however:

  • renameCollection will block all database activity for the duration of the operation.
  • renameCollection is incompatible with sharded collections.

Warning

renameCollection will fail if target is the name of an existing collection and you do not specify dropTarget: true.

If the renameCollection operation does not complete the target collection 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:

db.source-namespace.renameCollection( "target" )

Warning

You cannot use renameCollection with sharded collections.

Warning

This command obtains a global write lock and will block other operations until it has completed.

MongoDB Manual 2.4

Formats

About MongoDB

MongoDB Ecosystem

MongoDB Resources