Skip to content

Commit 280b0f7

Browse files
authored
DOCSP-41969: Replace documents (#125)
* DOCSP-41969: Replace documents * edits * wording * SA * JT feedback
1 parent f7d2584 commit 280b0f7

File tree

3 files changed

+254
-1
lines changed

3 files changed

+254
-1
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 = $collection->replaceOne(
38+
['name' => 'Food Town'],
39+
$replace_document,
40+
['upsert' => true]
41+
);
42+
// end-replace-options

source/write.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ Write Data to MongoDB
77
.. toctree::
88
:titlesonly:
99
:maxdepth: 1
10-
10+
11+
/write/replace
1112
/write/insert
1213
/write/update

source/write/replace.txt

Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
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 {+php-library+} to run a replace
24+
operation on a MongoDB collection. A replace operation performs differently
25+
than an update operation. An update operation modifies only the specified
26+
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 ``MongoDB\Collection::replaceOne()``.
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+
Example
102+
~~~~~~~
103+
104+
The following example uses the ``replaceOne()`` method to replace the fields and values
105+
of a document in which the ``name`` field value is ``'Pizza Town'``. It then prints
106+
the number of modified documents:
107+
108+
.. io-code-block::
109+
:copyable:
110+
111+
.. input:: /includes/write/replace.php
112+
:start-after: start-replace-one
113+
:end-before: end-replace-one
114+
:language: php
115+
:dedent:
116+
117+
.. output::
118+
:visible: false
119+
120+
Modified documents: 1
121+
122+
.. important::
123+
124+
The values of ``_id`` fields are immutable. If your replacement document specifies
125+
a value for the ``_id`` field, it must match the ``_id`` value of the existing document.
126+
127+
Modify the Replace Operation
128+
----------------------------
129+
130+
You can modify the behavior of the ``MongoDB\Collection::replaceOne()`` method
131+
by passing an array that specifies option values as a parameter. The following
132+
table describes some options you can set in the array:
133+
134+
.. list-table::
135+
:widths: 30 70
136+
:header-rows: 1
137+
138+
* - Option
139+
- Description
140+
141+
* - ``upsert``
142+
- | Specifies whether the replace operation performs an upsert operation if no
143+
documents match the query filter. For more information, see the :manual:`upsert
144+
statement </reference/command/update/#std-label-update-command-upsert>`
145+
in the {+mdb-server+} manual.
146+
| Defaults to ``false``.
147+
148+
* - ``bypassDocumentValidation``
149+
- | Specifies whether the replace operation bypasses document validation. This lets you
150+
replace documents that don't meet the schema validation requirements, if any
151+
exist. For more information about schema validation, see :manual:`Schema
152+
Validation </core/schema-validation/#schema-validation>` in the MongoDB
153+
Server manual.
154+
| Defaults to ``false``.
155+
156+
* - ``collation``
157+
- | Specifies the kind of language collation to use when sorting
158+
results. For more information, see :manual:`Collation </reference/collation/#std-label-collation>`
159+
in the {+mdb-server+} manual.
160+
161+
* - ``hint``
162+
- | Gets or sets the index to scan for documents.
163+
For more information, see the :manual:`hint statement </reference/command/update/#std-label-update-command-hint>`
164+
in the {+mdb-server+} manual.
165+
166+
* - ``session``
167+
- | Specifies the client session to associate with the operation.
168+
169+
* - ``let``
170+
- | Specifies a document with a list of values to improve operation readability.
171+
Values must be constant or closed expressions that don't reference document
172+
fields. For more information, see the :manual:`let statement
173+
</reference/command/update/#std-label-update-let-syntax>` in the
174+
{+mdb-server+} manual.
175+
176+
* - ``comment``
177+
- | Attaches a comment to the operation. For more information, see the :manual:`insert command
178+
fields </reference/command/insert/#command-fields>` guide in the
179+
{+mdb-server+} manual.
180+
181+
Example
182+
~~~~~~~
183+
184+
The following code uses the ``replaceOne()`` method to find the first document
185+
in which the ``name`` field has the value ``'Food Town'``, then replaces this document
186+
with a new document in which the ``name`` value is ``'Food World'``. Because the
187+
``upsert`` option is set to ``true``, the library inserts a new document if the query
188+
filter doesn't match any existing documents:
189+
190+
.. literalinclude:: /includes/write/replace.php
191+
:start-after: start-replace-options
192+
:end-before: end-replace-options
193+
:language: php
194+
:copyable:
195+
196+
Additional Information
197+
----------------------
198+
199+
To learn more about update operations, see the :ref:`php-write-update` guide.
200+
201+
To learn more about creating query filters, see the :ref:`php-specify-query` guide.
202+
203+
API Documentation
204+
~~~~~~~~~~~~~~~~~
205+
206+
To learn more about any of the methods or types discussed in this
207+
guide, see the following API documentation:
208+
209+
- `MongoDB\\Collection::replaceOne() <{+api+}/method/MongoDBCollection-replaceOne/>`__
210+
- `MongoDB\\UpdateResult <{+api+}/class/MongoDBUpdateResult/>`__

0 commit comments

Comments
 (0)