=======================================
MongoDB\\Collection::findOneAndUpdate()
=======================================

.. default-domain:: mongodb

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

Definition
----------

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

   Finds a single document matching the query and updates it.

   .. code-block:: php

      function findOneAndUpdate(
          array|object $filter,
          array|object $update,
          array $options = []
      ): object|null

Parameters
----------

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

``$update`` : array|object
  Specifies the field and value combinations to update and any relevant update
  operators. ``$update`` uses MongoDB's :manual:`update operators
  </reference/operator/update>`. Starting with MongoDB 4.2, an `aggregation
  pipeline <https://mongodb.com/docs/master/reference/command/update/#update-with-an-aggregation-pipeline>`_
  can be passed as this parameter.

``$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``.

     * - arrayFilters
       - array
       - An array of filter documents that determines which array elements to
         modify for an update operation on an array field.

         .. versionadded:: 1.3

     * - 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

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

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

         .. versionadded:: 1.13

     * - 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 update is applied,
         or after. ``returnDocument`` supports the following values:

         - ``MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_BEFORE`` (*default*)
         - ``MongoDB\Operation\FindOneAndUpdate::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 or object for either the original or the updated 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
--------

The following operation updates the restaurant with ``restaurant_id`` of
``"40361708"`` in the ``restaurants`` collection in the ``test`` database by
setting its building number to ``"761"``:

.. code-block:: php

   <?php

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

   $updatedRestaurant = $collection->findOneAndUpdate(
       [ 'restaurant_id' => '40361708' ],
       [ '$set' => [ 'address.building' => '761' ]],
       [
           'projection' => [ 'address' => 1 ],
           'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
       ]
   );

   var_dump($updatedRestaurant);

The output would then resemble:

.. code-block:: none

   object(MongoDB\Model\BSONDocument)#20 (1) {
     ["storage":"ArrayObject":private]=>
     array(2) {
       ["_id"]=>
       object(MongoDB\BSON\ObjectId)#12 (1) {
         ["oid"]=>
         string(24) "594d5ef280a846852a4b3dee"
       }
       ["address"]=>
       object(MongoDB\Model\BSONDocument)#19 (1) {
         ["storage":"ArrayObject":private]=>
         array(4) {
           ["building"]=>
           string(3) "761"
           ["coord"]=>
           object(MongoDB\Model\BSONArray)#18 (1) {
             ["storage":"ArrayObject":private]=>
             array(2) {
               [0]=>
               float(-73.9925306)
               [1]=>
               float(40.7309346)
             }
           }
           ["street"]=>
           string(8) "Broadway"
           ["zipcode"]=>
           string(5) "10003"
         }
       }
     }
   }

See Also
--------

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