Docs Menu

MongoDB\Database::selectCollection()

MongoDB\Database::selectCollection()

Selects a collection within the database. This method is aliased by MongoDB\Database::getCollection() and will be replaced by it in a future release.

function selectCollection(
string $collectionName,
array $options = []
): MongoDB\Collection
$collectionName : string
The name of the collection to select.
$options : array

An array specifying the desired options.

Name
Type
Description

codec

MongoDB\Codec\DocumentCodec

The default codec to use for collection operations.

New in version 1.17.

readConcern

The default read concern to use for collection operations. Defaults to the database's read concern.

readPreference

The default read preference to use for collection operations. Defaults to the database's read preference.

typeMap

array

The default type map to use for collection operations. Defaults to the database's type map.

writeConcern

The default write concern to use for collection operations. Defaults to the database's write concern.

A MongoDB\Collection object.

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

The selected collection inherits options such as read preference and type mapping from the Database object. Options may be overridden by using the $options parameter.

The following example selects the users collection in the test database:

<?php
$db = (new MongoDB\Client)->test;
$collection = $db->selectCollection('users');

The following example selects the users collection in the test database with a custom read preference:

<?php
$db = (new MongoDB\Client)->test;
$users = $db->selectCollection(
'users',
[
'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'),
]
);