Para agentes de IA: hay un índice de documentación disponible en https://www.mongodb.com/es/docs/llms.txt — versiones en markdown de todas las páginas están disponibles agregando .md a cualquier ruta URL.
Docs Menu

renameCollection (comando de base de datos)

renameCollection

Changes the name of an existing collection. Specify collection names to renameCollection in the form of a complete namespace (<database>.<collection>).

Tip

In mongosh, this command can also be run through the renameCollection() helper method.

Helper methods are convenient for mongosh users, but they may not return the same level of information as database commands. In cases where the convenience is not needed or the additional return fields are required, use the database command.

Issue the renameCollection command against the admin database.

Este comando está disponible en implementaciones alojadas en los siguientes entornos:

  • MongoDB Atlas: El servicio totalmente gestionado para implementaciones de MongoDB en la nube

Nota

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.

  • MongoDB Enterprise: La versión basada en suscripción y autogestionada de MongoDB

  • MongoDB Community: La versión de MongoDB con código fuente disponible, de uso gratuito y autogestionada.

El comando tiene la siguiente sintaxis:

db.runCommand(
{
renameCollection: "<source_namespace>",
to: "<target_namespace>",
dropTarget: <true|false>,
writeConcern: <document>,
comment: <any>
}
)

El comando contiene los siguientes campos:

Campo
Tipo
Descripción

renameCollection

string

El namespace de la colección que se desea renombrar. El namespace es una combinación del nombre de la base de datos y el nombre de la colección.

to

string

The new namespace of the collection. If the new namespace specifies a different database, the renameCollection command copies the collection to the new database and drops the source collection. See Naming Restrictions.

En las implementaciones de MongoDB Atlas, el rol atlasAdmin solo otorga la acción de privilegio renameCollectionSameDB, por lo que no puede cambiar el nombre de una colección a una base de datos diferente.

dropTarget

booleano

Optional. If true, mongod will drop the target of renameCollection prior to renaming the collection. The default value is false.

writeConcern

Documento

Opcional. Un documento que expresa el nivel de confirmación de escritura para la operación. Omite usar el nivel de confirmación de escritura por defecto.

When issued on a sharded cluster, mongos converts the write concern of the renameCollection command and its helper db.collection.renameCollection() to "majority".

comment

any

Opcional. Un comentario proporcionado por el usuario para adjuntar a este comando. Una vez configurado, este comentario aparece junto a los registros de este comando en las siguientes ubicaciones:

Un comentario puede ser de cualquier tipo BSON válido (string, objeto, arreglo, etc.).

A partir de MongoDB,5.0 puede usar el comando para cambiar el nombre de una colección fragmentada. La base de datos de destino debe ser la misma que la base de datos de renameCollection origen.

You can use renameCollection to rename an unsharded collection in a sharded cluster as long as the source and target databases are on the same primary shard.

You cannot use renameCollection to rename a time series collection. For more information, see Time Series Collection Limitations.

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

The rename operation fails with a BackgroundOperationInProgressForNamespace error if an index build is in progress on the source collection. The operation also fails if an index build is in progress on the target collection and you specify dropTarget: true.

To rename the collection, wait for the index build to finish and then retry the operation. To check for in-progress index builds, use the db.currentOp() method.

Cambiado en la versión 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.

Cambiado en la versión 5.0.

Al cambiar el nombre de una colección particionada o no particionada en un clúster, las colecciones de origen y destino se bloquean exclusivamente en cada partición. Las operaciones posteriores en las colecciones de origen y destino deben esperar hasta que se complete la operación de cambio de nombre.

Para obtener más información sobre el bloqueo en MongoDB, consulta FAQ: Concurrency.

If renaming a collection within the same database, renameCollection obtains an exclusive lock on the source and target collections for the duration of the operation. All subsequent operations on the collections must wait until renameCollection completes.

If renaming a collection between different databases, renameCollection obtains an exclusive (W) lock on the target database, an intent shared (r) lock on the source database, and a shared (S) lock on the source collection. Subsequent operations on the target database must wait until renameCollection releases the exclusive database lock.

Para obtener más información sobre el bloqueo en MongoDB, consulta FAQ: Concurrency.

  • No puede renombrar una colección de una base de datos replicada a la base de datos local, que no está replicada.

  • No se puede cambiar el nombre de una colección de la base de datos local, que no está replicada, a una base de datos replicada.

Advertencia

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

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

A mongodump started with --oplog fails if a client issues the renameCollection command during the dump process. See mongodump.--oplog for more information.

El siguiente ejemplo renombra una colección llamada orders en la base de datos test a orders2014 en la base de datos test.

db.adminCommand( { renameCollection: "test.orders", to: "test.orders2014" } )

mongosh 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" )