On this page
renameCollection
On this page
Definition
renameCollection-
Changes the name of an existing collection. Specify collection names to
renameCollectionin the form of a complete namespace (<database>.<collection>).Issue the
renameCollectioncommand against the admin database.The command takes the following form:
{ renameCollection: "<source_namespace>", to: "<target_namespace>", dropTarget: <true|false> writeConcern: <document> }The command contains the following fields:
Field Type Description renameCollectionstring The namespace of the collection to rename. The namespace is a combination of the database name and the name of the collection. tostring The new namespace of the collection. If the new namespace specifies a different database, the renameCollectioncommand copies the collection to the new database and drops the source collection. See Naming Restrictions.dropTargetboolean Optional. If true,mongodwill drop thetargetofrenameCollectionprior to renaming the collection. The default value isfalse.writeConcerndocument Optional. A document that expresses the write concern for the operation. Omit to use the default write concern.
Behavior
Existing Target Collection
renameCollection fails if target is the name of an existing collection and you do not specify dropTarget: true.
Performance
Changed in version 3.6.
renameCollection has different performance implications depending on the target namespace.
If the target database is the same as the source database, renameCollection simply changes the namespace. This is a quick operation.
If the target database differs from the source database, renameCollection copies all documents from the source collection to the target collection. Depending on the size of the collection, this may take longer to complete. Other operations which require exclusive access to the affected databases will be blocked until the rename completes. See What locks are taken by some common client operations? for operations which require exclusive access to all databases.
Example
The following example renames a collection named orders in the test database to orders2014 in the test database.
db.adminCommand( { 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" )