Navigation

db.collection.renameCollection()

On this page

Definition

db.collection.renameCollection(target, dropTarget)

mongo Shell Method

This page documents the mongo shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.

Renames a collection. Provides a wrapper for the renameCollection database command.

Parameter Type Description
target string The new name of the collection. Enclose the string in quotes. See Naming Restrictions.
dropTarget boolean Optional. If true, mongod drops the target of renameCollection prior to renaming the collection. The default value is false.

Behavior

The db.collection.renameCollection() method operates within a collection by changing the metadata associated with a given collection.

Refer to the documentation renameCollection for additional warnings and messages.

Warning

The db.collection.renameCollection() method and renameCollection command will invalidate open cursors which interrupts queries that are currently returning data.

For Change Streams, the db.collection.renameCollection() method and renameCollection command create an invalidate Event for any existing Change Streams opened on the source or target collection.

Resource Locking

Changed in version 4.2.

db.collection.renameCollection() obtains an exclusive lock on the specified collections for the duration of the operation. All subsequent operations on the collections must wait until db.collection.renameCollection() releases the lock.

Prior to MongoDB 4.2, db.collection.renameCollection() obtained an exclusive lock on the parent database, blocking all operations on the database and all its collections until the operation completed.

Example

Call the db.collection.renameCollection() method on a collection object. For example:

db.rrecord.renameCollection("record")

This operation will rename the rrecord collection to record. If the target name (i.e. record) is the name of an existing collection, then the operation will fail.