MongoDBCollection-replaceOne.txt 2.49 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
Errors/Exceptions
-----------------

.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
45
.. include:: /includes/extracts/error-driver-bulkwriteexception.rst
46 47
.. include:: /includes/extracts/error-driver-runtimeexception.rst

48 49 50 51
Behavior
--------

.. include:: /includes/extracts/note-bson-comparison.rst
52
.. include:: /includes/extracts/bulkwriteexception-result.rst
53

54 55 56
Example
-------

57
The following example replaces the document with ``restaurant_id`` of
58
``"40356068"`` in the ``restaurants`` collection in the ``test`` database:
59 60

.. code-block:: php
61

62 63
   <?php

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

66 67
   $updateResult = $collection->replaceOne(
       [ 'restaurant_id' => '40356068' ],
68 69 70 71 72 73 74 75 76
       [
           'name' => 'New Restaurant',
           'restaurant_id' => '99988877',
           'borough' => 'Queens',
           'cuisine' => 'Cafe',
           'grades' => [],
       ]
   );

77 78 79 80 81 82 83
   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)
84

85 86 87 88 89 90 91 92 93
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