=====================================
MongoDB\\Database::selectCollection()
=====================================

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 1
   :class: singlecol

Definition
----------

.. phpmethod:: MongoDB\Database::selectCollection()

   Selects a collection within the database.

   .. code-block:: php

      function selectCollection(
          string $collectionName,
          array $options = []
      ): MongoDB\Collection

Parameters
----------

``$collectionName`` : string
  The name of the collection to select.

``$options`` : array
  An array specifying the desired options.

  .. list-table::
     :header-rows: 1
     :widths: 20 20 80

     * - Name
       - Type
       - Description

     * - codec
       - MongoDB\\Codec\\DocumentCodec
       - The default :doc:`codec </tutorial/codecs>` to use for collection
         operations.

         .. versionadded:: 1.17

     * - readConcern
       - :php:`MongoDB\Driver\ReadConcern <class.mongodb-driver-readconcern>`
       - The default read concern to use for collection operations. Defaults to
         the database's read concern.

     * - readPreference
       - :php:`MongoDB\Driver\ReadPreference <class.mongodb-driver-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
       - :php:`MongoDB\Driver\WriteConcern <class.mongodb-driver-writeconcern>`
       - The default write concern to use for collection operations. Defaults to
         the database's write concern.

Return Values
-------------

A :phpclass:`MongoDB\Collection` object.

Errors/Exceptions
-----------------

.. include:: /includes/extracts/error-invalidargumentexception.rst

Behavior
--------

The selected collection inherits options such as read preference and type
mapping from the :phpclass:`Database <MongoDB\Database>` object. Options may be
overridden via the ``$options`` parameter.

Example
-------

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

.. code-block:: php

   <?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:

.. code-block:: php

   <?php

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

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

See Also
--------

- :phpmethod:`MongoDB\Database::__get()`
- :phpmethod:`MongoDB\Client::selectCollection()`
- :phpmethod:`MongoDB\Collection::__construct()`
