==================================
MongoDB\\Collection::withOptions()
==================================

.. default-domain:: mongodb

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

Definition
----------

.. phpmethod:: MongoDB\Collection::withOptions()

   Returns a clone of the Collection object, but with different options.

   .. code-block:: php

      function withOptions(array $options = []): MongoDB\Collection

Parameters
----------

``$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. Defaults to the original collection's codec.

         .. versionadded:: 1.17

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

     * - readPreference
       - :php:`MongoDB\Driver\ReadPreference <class.mongodb-driver-readpreference>`
       - The default read preference to use for collection operations. Defaults
         to the original collection's read preference.

     * - typeMap
       - array
       - The :php:`type map
         <manual/en/mongodb.persistence.deserialization.php#mongodb.persistence.typemaps>`
         to apply to cursors, which determines how BSON documents are converted
         to PHP values. Defaults to the original collection's type map.

     * - writeConcern
       - :php:`MongoDB\Driver\WriteConcern <class.mongodb-driver-writeconcern>`
       - The default write concern to use for collection operations. Defaults to
         the original collection's write concern.

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

A :phpclass:`MongoDB\Collection` object.

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

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

Example
-------

The following example clones an existing Collection object with a new read
preference:

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->selectCollection('test', 'restaurants');

   $newCollection = $sourceCollection->withOptions([
       'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'),
   ]);

See Also
--------

- :phpmethod:`MongoDB\Collection::__construct()`
