Navigation

MongoDB\Database::renameCollection()

New in version 1.10.

Definition

MongoDB\Database::renameCollection

Rename a collection within the current database.

function renameCollection(string $fromCollectionName, string $toCollectionName, ?string $toDatabaseName = null, array $options = []): array|object

This method has the following parameters:

Parameter Type Description
$fromCollectionName string The name of the collection to rename.
$toCollectionName string The new name of the collection.
$toDatabaseName string Optional. The new database name of the collection. If a new database name is not specified, the current database will be used. If the new name specifies a different database, the command copies the collection to the new database and drops the source collection.
$options array Optional. An array specifying the desired options.

The $options parameter supports the following options:

Option Type Description
session MongoDB\Driver\Session

Optional. Client session to associate with the operation.

Sessions are not supported for server versions prior to 3.6.

typeMap array

Optional. The type map to apply to cursors, which determines how BSON documents are converted to PHP values. Defaults to the database’s type map.

This will be used for the returned command result document.

writeConcern MongoDB\Driver\WriteConcern

Optional. Write concern to use for the operation. Defaults to the database’s write concern.

This is not supported for server versions prior to 3.4 and will result in an exception at execution time if used.

dropTarget boolean Optional. If true, MongoDB will drop the target before renaming the collection. The default value is false.

Return Values

An array or object with the result document of the renameCollection command. The return type will depend on the typeMap option.

Errors/Exceptions

MongoDB\Exception\UnsupportedException if options are used and not supported by the selected server (e.g. collation, readConcern, writeConcern).

MongoDB\Exception\InvalidArgumentException for errors related to the parsing of parameters or options.

MongoDB\Driver\Exception\RuntimeException for other errors at the driver level (e.g. connection errors).

Example

The following example renames the restaurants collection in the test database to places:

<?php

$db = (new MongoDB\Client)->test;

$result = $db->renameCollection('restaurants', 'places');

var_dump($result);

The output would then resemble:

object(MongoDB\Model\BSONDocument)#8 (1) {
  ["storage":"ArrayObject":private]=>
  array(1) {
    ["ok"]=>
    float(1)
  }
}

See Also