Skip to content

Commit 3fa67b8

Browse files
committed
DOCSP-41969: Replace documents
1 parent 7e0f9be commit 3fa67b8

File tree

3 files changed

+261
-0
lines changed

3 files changed

+261
-0
lines changed

source/includes/write/replace.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
require 'vendor/autoload.php';
3+
4+
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
5+
$client = new MongoDB\Client($uri);
6+
7+
// start-db-coll
8+
$collection = $client->sample_restaurants->restaurants;
9+
// end-db-coll
10+
11+
// start-replace-one
12+
$replace_document = [
13+
'name' => 'Mongo\'s Pizza',
14+
'cuisine' => 'Pizza',
15+
'address' => [
16+
'street' => '123 Pizza St',
17+
'zipCode' => '10003',
18+
],
19+
'borough' => 'Manhattan'
20+
];
21+
22+
$result = $collection->replaceOne(['name' => 'Pizza Town'], $replace_document);
23+
echo 'Modified documents: ' . $result->getModifiedCount();
24+
// end-replace-one
25+
26+
// start-replace-options
27+
$replace_document = [
28+
'name' => 'Food World',
29+
'cuisine' => 'Mixed',
30+
'address' => [
31+
'street' => '123 Food St',
32+
'zipCode' => '10003',
33+
],
34+
'borough' => 'Manhattan'
35+
];
36+
37+
$result_two = $collection->replaceOne(
38+
['name' => 'Food Town'],
39+
$replace_document,
40+
['upsert' => true]
41+
);
42+
// end-replace-options

source/write.txt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
.. _php-write:
2+
3+
=====================
4+
Write Data to MongoDB
5+
=====================
6+
7+
.. toctree::
8+
:titlesonly:
9+
:maxdepth: 1
10+
11+
/write/replace

source/write/replace.txt

Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
.. _php-write-replace:
2+
3+
=================
4+
Replace Documents
5+
=================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: modify, change, code example
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+library-short+} to perform a replace
24+
operation on a document in a MongoDB collection. A replace operation performs
25+
differently than an update operation. An update operation modifies only the
26+
specified fields in a target document. A replace operation removes *all* fields
27+
in the target document and replaces them with new ones.
28+
29+
To replace a document, use the ``MongoDB\Collection::replaceOne()`` method.
30+
31+
Sample Data
32+
~~~~~~~~~~~
33+
34+
The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
35+
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
36+
from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster
37+
and assign the following value to your ``$collection`` variable:
38+
39+
.. literalinclude:: /includes/read/project.php
40+
:language: php
41+
:dedent:
42+
:start-after: start-db-coll
43+
:end-before: end-db-coll
44+
45+
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
46+
:atlas:`Get Started with Atlas </getting-started>` guide.
47+
48+
Replace Operation
49+
-----------------
50+
51+
You can perform a replace operation by using the ``MongoDB\Collection::replaceOne()`` method.
52+
This method removes all fields except the ``_id`` field from the first document that
53+
matches the search criteria. It then inserts the fields and values you specify into the
54+
document.
55+
56+
Required Parameters
57+
~~~~~~~~~~~~~~~~~~~
58+
59+
The ``replaceOne()`` method requires the following parameters:
60+
61+
- **Query filter** document, which determines the documents to replace. For
62+
more information about query filters, see the
63+
:manual:`Query Filter Documents section </core/document/#query-filter-documents>` in
64+
the {+mdb-server+} manual.
65+
- **Replace** document, which specifies the fields and values to insert in the new
66+
document.
67+
68+
Return Value
69+
~~~~~~~~~~~~
70+
71+
The ``replaceOne()`` method returns a ``MongoDB\UpdateResult``
72+
object. The ``MongoDB\UpdateResult`` type contains the following
73+
methods:
74+
75+
.. list-table::
76+
:widths: 30 70
77+
:header-rows: 1
78+
79+
* - Method
80+
- Description
81+
82+
* - ``getMatchedCount()``
83+
- | Returns the number of documents that matched the query filter, regardless of
84+
how many were updated.
85+
86+
* - ``getModifiedCount()``
87+
- | Returns the number of documents modified by the update operation. If an updated
88+
document is identical to the original, it is not included in this
89+
count.
90+
91+
* - ``getUpsertedCount()``
92+
- | Returns the number of documents upserted into the database, if any.
93+
94+
* - ``getUpsertedId()``
95+
- | Returns the ID of the document that was upserted in the database, if the driver
96+
performed an upsert.
97+
98+
* - ``isAcknowledged()``
99+
- | Returns a boolean indicating whether the write operation was acknowledged.
100+
101+
102+
103+
Example
104+
~~~~~~~
105+
106+
The following example uses the ``replaceOne()`` method to replace the fields and values
107+
of a document in which the ``name`` field value is ``'Pizza Town'``:
108+
109+
.. io-code-block::
110+
:copyable:
111+
112+
.. input:: /includes/write/update.php
113+
:start-after: start-replace-one
114+
:end-before: end-replace-one
115+
:language: php
116+
:dedent:
117+
118+
.. output::
119+
:visible: false
120+
121+
Modified documents: 1
122+
123+
.. important::
124+
125+
The values of ``_id`` fields are immutable. If your replacement document specifies
126+
a value for the ``_id`` field, it must match the ``_id`` value of the existing document.
127+
128+
Modify the Replace Operation
129+
----------------------------
130+
131+
You can modify the behavior of the ``MongoDB\Collection::replaceOne()`` method
132+
by passing an array that specifies option values as a parameter. The following
133+
table describes some options you can set in the array:
134+
135+
.. list-table::
136+
:widths: 30 70
137+
:header-rows: 1
138+
139+
* - Option
140+
- Description
141+
142+
* - ``upsert``
143+
- | Specifies whether the replace operation performs an upsert operation if no
144+
documents match the query filter. For more information, see the :manual:`upsert
145+
statement </reference/command/update/#std-label-update-command-upsert>`
146+
in the {+mdb-server+} manual.
147+
| Defaults to ``false``
148+
149+
* - ``bypassDocumentValidation``
150+
- | Specifies whether the replace operation bypasses document validation. This lets you
151+
replace documents that don't meet the schema validation requirements, if any
152+
exist. For more information about schema validation, see :manual:`Schema
153+
Validation </core/schema-validation/#schema-validation>` in the MongoDB
154+
Server manual.
155+
| Defaults to ``false``.
156+
157+
* - ``collation``
158+
- | Specifies the kind of language collation to use when sorting
159+
results. For more information, see :manual:`Collation </reference/collation/#std-label-collation>`
160+
in the {+mdb-server+} manual.
161+
162+
* - ``hint``
163+
- | Gets or sets the index to scan for documents.
164+
For more information, see the :manual:`hint statement </reference/command/update/#std-label-update-command-hint>`
165+
in the {+mdb-server+} manual.
166+
167+
* - ``session``
168+
- | An instance of ``ClientSession``.
169+
170+
* - ``let``
171+
- | Specifies a document with a list of values to improve operation readability.
172+
Values must be constant or closed expressions that don't reference document
173+
fields. For more information, see the :manual:`let statement
174+
</reference/command/update/#std-label-update-let-syntax>` in the
175+
{+mdb-server+} manual.
176+
177+
* - ``comment``
178+
- | Attaches a comment to the operation. For more information, see the :manual:`insert command
179+
fields </reference/command/insert/#command-fields>` guide in the
180+
{+mdb-server+} manual.
181+
182+
The following code uses the ``replaceOne()`` method to find the first document
183+
in which the ``name`` field has the value ``'Food Town'``, then replaces this document
184+
with a new document in which the ``name`` value is ``'Food World'``. Because the
185+
``upsert`` option is set to ``true``, the library inserts a new document if the query
186+
filter doesn't match any existing documents.
187+
188+
.. literalinclude:: /includes/write/replace.php
189+
:start-after: start-replace-options
190+
:end-before: end-replace-options
191+
:language: php
192+
:copyable:
193+
194+
Additional Information
195+
----------------------
196+
197+
To learn more about update operations, see the :ref:`php-write-update` guide.
198+
199+
To learn more about creating query filters, see the :ref:`php-specify-query` guide.
200+
201+
API Documentation
202+
~~~~~~~~~~~~~~~~~
203+
204+
To learn more about any of the methods or types discussed in this
205+
guide, see the following API documentation:
206+
207+
- `MongoDB\\Collection::replaceOne() <{+api+}/reference/method/MongoDBCollection-replaceOne/>`__
208+
- `MongoDB\\UpdateResult <{+api+}/reference/class/MongoDBUpdateResult/>`__

0 commit comments

Comments
 (0)