db.collection.renameCollection()

Definition

  • db.collection.renameCollection(target, dropTarget)

mongo Shell Method

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

Renames a collection. Provides a wrapper for therenameCollectiondatabase command.

ParameterTypeDescriptiontargetstringThe new name of the collection. Enclose the string in quotes.See Naming Restrictions.dropTargetbooleanOptional. If true, mongod drops the target of renameCollection prior torenaming the collection. The default value is false.

Behavior

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

Refer to the documentation renameCollection for additionalwarnings and messages.

Warning

The db.collection.renameCollection() method andrenameCollection command will invalidate open cursorswhich interrupts queries that are currently returning data.

For Change Streams, thedb.collection.renameCollection() method andrenameCollection command create aninvalidate Event for any existingChange Streams opened on the source or target collection.

Resource Locking

Changed in version 4.2.

db.collection.renameCollection() obtains an exclusive lockon the specified collections for the duration of the operation. Allsubsequent operations on the collections must wait untildb.collection.renameCollection() releases the lock.

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

Example

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

  1. db.rrecord.renameCollection("record")

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