MongoDBCollection-replaceOne.txt 2.29 KB
Newer Older
1 2 3 4 5
=================================
MongoDB\\Collection::replaceOne()
=================================

.. default-domain:: mongodb
6

7 8 9 10 11 12 13 14 15
.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 1
   :class: singlecol

Definition
----------

16 17 18 19 20 21
.. phpmethod:: MongoDB\\Collection::replaceOne()

   Replace at most one document that matches the filter criteria. If multiple
   documents match the filter criteria, only the :term:`first <natural order>`
   matching document will be replaced.

22
   .. code-block:: php
23

24 25
      function replaceOne($filter, $replacement, array $options = []): MongoDB\UpdateResult

26
   This method has the following parameters:
27

28 29 30
   .. include:: /includes/apiargs/MongoDBCollection-method-replaceOne-param.rst

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

32 33
   .. include:: /includes/apiargs/MongoDBCollection-method-replaceOne-option.rst

34 35
Return Values
-------------
36

37 38
A :phpclass:`MongoDB\\UpdateResult` object, which encapsulates a
:php:`MongoDB\\Driver\\WriteResult <class.mongodb-driver-writeresult>` object.
39

40 41 42 43 44 45 46
Errors/Exceptions
-----------------

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

47 48 49
Example
-------

50 51
The following example replaces the document with ``restaurant_id`` of
``"40356068"`` in the ``restaurants`` collection in the ``example`` database:
52 53

.. code-block:: php
54

55 56
   <?php

57
   $collection = (new MongoDB\Client)->example->restaurants;
58

59 60
   $updateResult = $collection->replaceOne(
       [ 'restaurant_id' => '40356068' ],
61 62 63 64 65 66 67 68 69
       [
           'name' => 'New Restaurant',
           'restaurant_id' => '99988877',
           'borough' => 'Queens',
           'cuisine' => 'Cafe',
           'grades' => [],
       ]
   );

70 71 72 73 74 75 76
   printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
   printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

The output would then resemble::

   Matched 1 document(s)
   Modified 1 document(s)
77

78 79 80 81 82 83 84 85 86
See Also
--------

- :phpmethod:`MongoDB\\Collection::updateMany()`
- :phpmethod:`MongoDB\\Collection::updateOne()`
- :phpmethod:`MongoDB\\Collection::bulkWrite()`
- :doc:`/tutorial/crud`
- :manual:`update </reference/command/update>` command reference in the MongoDB
  manual