MongoDBDatabase-selectCollection.txt 1.79 KB
=====================================
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($collectionName, array $options = []): MongoDB\Collection

   :phpmethod:`MongoDB\\Database::selectCollection()` has the following
   parameters:

   .. include:: /includes/apiargs/MongoDBDatabase-method-selectCollection-param.rst

   The ``$options`` parameter supports the following options:

   .. include:: /includes/apiargs/MongoDBDatabase-method-selectCollection-option.rst

   :returns:

      A :phpclass:`MongoDB\\Collection` object.

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 ``demo`` database:

.. code-block:: php

   <?php

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

   $collection = $db->selectCollection('demo', 'users');

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

.. code-block:: php

   <?php

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

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

.. seealso::

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