========================================
MongoDB\\Collection::findOneAndReplace()
========================================

.. default-domain:: mongodb

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

Definition
----------

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

   Finds a single document matching the query and replaces it.

   .. code-block:: php

      function findOneAndReplace(
          array|object $filter,
          array|object $replacement,
          array $options = []
      ): object|null

Parameters
----------

``$filter`` : array|object
  The filter criteria that specifies the documents to replace.

``$replacement`` : array|object
  The replacement document.

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

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

     * - Name
       - Type
       - Description

     * - bypassDocumentValidation
       - boolean
       - If ``true``, allows the write operation to circumvent document level
         validation. Defaults to ``false``.

     * - codec
       - MongoDB\\Codec\\DocumentCodec
       - .. include:: /includes/extracts/collection-option-codec.rst

         .. versionadded:: 1.17

     * - collation
       - array|object
       - .. include:: /includes/extracts/collection-option-collation.rst

     * - comment
       - mixed
       - .. include:: /includes/extracts/common-option-comment.rst

         .. include:: /includes/extracts/option-requires-4.4.rst

         .. versionadded:: 1.13

     * - hint
       - string|array|object
       - .. include:: /includes/extracts/common-option-hint.rst

         .. include:: /includes/extracts/option-requires-4.4.rst

         .. versionadded:: 1.7

     * - let
       - array|object
       - .. include:: /includes/extracts/common-option-let.rst

         .. versionadded:: 1.13

     * - maxTimeMS
       - integer
       - .. include:: /includes/extracts/common-option-maxTimeMS.rst

     * - projection
       - array|object
       - The :ref:`projection specification <projections>` to determine which
         fields to include in the returned documents. See
         :manual:`Project Fields to Return from Query </tutorial/project-fields-from-query-results>`
         and :manual:`Projection Operators </reference/operator/projection>` in
         the MongoDB manual.

     * - returnDocument
       - integer
       - Specifies whether to return the document before the replacement is
         applied, or after. ``returnDocument`` supports the following values:

         - ``MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_BEFORE`` (*default*)
         - ``MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_AFTER``

     * - session
       - :php:`MongoDB\Driver\Session <class.mongodb-driver-session>`
       - .. include:: /includes/extracts/common-option-session.rst

         .. versionadded:: 1.3

     * - sort
       - array|object
       - The sort specification for the ordering of the results.

     * - typeMap
       - array
       - .. include:: /includes/extracts/collection-option-typeMap.rst

         This will be used for the returned result document.

     * - upsert
       - boolean
       - If set to ``true``, creates a new document when no document matches the
         query criteria. The default value is ``false``, which does not insert a
         new document when no match is found.

     * - writeConcern
       - :php:`MongoDB\Driver\WriteConcern <class.mongodb-driver-writeconcern>`
       - .. include:: /includes/extracts/collection-option-writeConcern.rst

         .. include:: /includes/extracts/common-option-writeConcern-transaction.rst

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

An array object for either the original or the replaced document, depending on
the specified value of the ``returnDocument`` option. By default, the original
document is returned. If no document matched the query, ``null`` is returned.
The return type will depend on the ``typeMap`` option.

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

.. include:: /includes/extracts/error-unexpectedvalueexception.rst
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst

Behavior
--------

.. include:: /includes/extracts/note-bson-comparison.rst

Examples
--------

Consider the following document in the ``restaurants`` collection in the
``test`` database:

.. code-block:: javascript

   {
     "_id" : ObjectId("576023c7b02fa9281da4139e"),
     "address" : {
       "building" : "977",
       "coord" : [
         -74.06940569999999,
         40.6188443
       ],
       "street" : "Bay Street",
       "zipcode" : "10305"
     },
     "borough" : "Staten Island",
     "cuisine" : "French",
     "grades" : [
       {
         "date" : ISODate("2014-08-15T00:00:00Z"),
         "grade" : "A",
         "score" : 7
       },
       {
         "date" : ISODate("2014-02-13T00:00:00Z"),
         "grade" : "A",
         "score" : 5
       },
       {
         "date" : ISODate("2013-06-07T00:00:00Z"),
         "grade" : "A",
         "score" : 11
       }
     ],
     "name" : "Zest",
     "restaurant_id" : "41220906"
   }

The following operation replaces the document with ``restaurant_id`` of
``"41220906"`` with a new document:

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->teset->restaurants;

   $replacedRestaurant = $collection->findOneAndReplace(
       [ 'restaurant_id' => '41220906' ],
       [
           'Borough' => 'Staten Island',
           'cuisine' => 'Italian',
           'grades' => [],
           'name' => 'Staten Island Pastaria',
           'restaurant_id' => '999999999',
       ],
       [ 'returnDocument' => MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_AFTER ]
   );

   var_dump($replacedRestaurant);

The output would then resemble:

.. code-block:: none

   object(MongoDB\Model\BSONDocument)#18 (1) {
     ["storage":"ArrayObject":private]=>
     array(6) {
       ["_id"]=>
       object(MongoDB\BSON\ObjectId)#11 (1) {
         ["oid"]=>
         string(24) "594d5ef380a846852a4b5837"
       }
       ["Borough"]=>
       string(13) "Staten Island"
       ["cuisine"]=>
       string(7) "Italian"
       ["grades"]=>
       object(MongoDB\Model\BSONArray)#17 (1) {
         ["storage":"ArrayObject":private]=>
         array(0) {
         }
       }
       ["name"]=>
       string(22) "Staten Island Pastaria"
       ["restaurant_id"]=>
       string(9) "999999999"
     }
   }

See Also
--------

- :phpmethod:`MongoDB\Collection::findOneAndDelete()`
- :phpmethod:`MongoDB\Collection::findOneAndUpdate()`
- :manual:`findAndModify </reference/command/findAndModify>` command reference
  in the MongoDB manual
