Skip to content

Commit 017275c

Browse files
authored
DOCSP-41968: Update documents (#118)
* DOCSP-41968: Update documents * snooty fix * edits
1 parent 429ea3b commit 017275c

File tree

4 files changed

+286
-0
lines changed

4 files changed

+286
-0
lines changed

source/includes/write/update.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
require 'vendor/autoload.php';
4+
5+
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
6+
$client = new MongoDB\Client($uri);
7+
8+
// start-db-coll
9+
$collection = $client->sample_restaurants->restaurants;
10+
// end-db-coll
11+
12+
// Updates the "name" value of a document from "Bagels N Buns" to "2 Bagels 2 Buns"
13+
// start-update-one
14+
$result = $collection->updateOne(
15+
['name' => 'Bagels N Buns'],
16+
['$set' => ['name' => '2 Bagels 2 Buns']]
17+
);
18+
// end-update-one
19+
20+
// Updates the "cuisine" value of documents from "Pizza" to "Pasta"
21+
// start-update-many
22+
$result = $collection->updateMany(
23+
['cuisine' => 'Pizza'],
24+
['$set' => ['cuisine' => 'Pasta']]
25+
);
26+
// end-update-many
27+
28+
// Updates the "borough" value of matching documents and inserts a document if none match
29+
// start-update-options
30+
$result = $collection->updateMany(
31+
['borough' => 'Manhattan'],
32+
['$set' => ['borough' => 'Manhattan (north)']],
33+
['upsert' => true]
34+
);
35+
// end-update-options
36+
37+
// Updates the "name" value of matching documents and prints the number of updates
38+
// start-update-result
39+
$result = $collection->updateMany(
40+
['name' => 'Dunkin\' Donuts'],
41+
['$set' => ['name' => 'Dunkin\'']]
42+
);
43+
echo 'Modified documents: ' . $result->getModifiedCount();
44+
// end-update-result
45+

source/index.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ MongoDB PHP Library
1212

1313
Get Started </get-started>
1414
/read
15+
/write
1516
/tutorial
1617
/upgrade
1718
/reference

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/update

source/write/update.txt

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
.. _php-write-update:
2+
3+
================
4+
Update 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, bulk, code example
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+php-library+} to update
24+
documents in a MongoDB collection. You can call the ``MongoDB\Collection::updateOne()``
25+
method to update a single document or the ``MongoDB\Collection::updateMany()``
26+
method to update multiple documents.
27+
28+
Sample Data
29+
~~~~~~~~~~~
30+
31+
The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
32+
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
33+
from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster
34+
and assign the following value to your ``collection`` variable:
35+
36+
.. literalinclude:: /includes/write/update.php
37+
:language: php
38+
:dedent:
39+
:start-after: start-db-coll
40+
:end-before: end-db-coll
41+
42+
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
43+
:atlas:`Get Started with Atlas </getting-started>` guide.
44+
45+
Update Operations
46+
-----------------
47+
48+
You can perform update operations in MongoDB by using the following methods:
49+
50+
- ``MongoDB\Collection::updateOne()``, which updates *the first document* that
51+
matches the search criteria
52+
- ``MongoDB\Collection::updateMany()``, which updates *all documents* that match
53+
the search criteria
54+
55+
Each update method requires the following parameters:
56+
57+
- **Query filter** document: Specifies which documents to update. For
58+
more information about query filters, see the
59+
:manual:`Query Filter Documents section </core/document/#query-filter-documents>` in
60+
the {+mdb-server+} manual.
61+
62+
- **Update** document: Specifies the **update operator**, or the kind of update to
63+
perform, and the fields and values to change. For a list of update operators
64+
and their usage, see the :manual:`Field Update Operators guide
65+
</reference/operator/update-field/>` in the {+mdb-server+} manual.
66+
67+
Update One Document
68+
~~~~~~~~~~~~~~~~~~~
69+
70+
The following example uses the ``updateOne()`` method to update the ``name``
71+
value of a document in the ``restaurants`` collection from ``'Bagels N Buns'``
72+
to ``'2 Bagels 2 Buns'``:
73+
74+
.. literalinclude:: /includes/write/update.php
75+
:start-after: start-update-one
76+
:end-before: end-update-one
77+
:language: php
78+
:dedent:
79+
80+
Update Many Documents
81+
~~~~~~~~~~~~~~~~~~~~~
82+
83+
The following example uses the ``updateMany()`` method to update all documents
84+
that have a ``cuisine`` value of ``'Pizza'``. After the update, the documents have
85+
a ``cuisine`` value of ``'Pasta'``.
86+
87+
.. literalinclude:: /includes/write/update.php
88+
:start-after: start-update-many
89+
:end-before: end-update-many
90+
:language: php
91+
:dedent:
92+
93+
Customize the Update Operation
94+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
95+
96+
You can modify the behavior of the ``updateOne()`` and ``updateMany()`` methods by
97+
passing an array that specifies option values as a parameter. The following table
98+
describes some options you can set in the array:
99+
100+
.. list-table::
101+
:widths: 30 70
102+
:header-rows: 1
103+
104+
* - Option
105+
- Description
106+
107+
* - ``upsert``
108+
- | Specifies whether the update operation performs an upsert operation if no
109+
documents match the query filter. For more information, see the :manual:`upsert
110+
statement </reference/command/update/#std-label-update-command-upsert>`
111+
in the {+mdb-server+} manual.
112+
| Defaults to ``false``.
113+
114+
* - ``bypassDocumentValidation``
115+
- | Specifies whether the update operation bypasses document validation. This lets you
116+
update documents that don't meet the schema validation requirements, if any
117+
exist. For more information about schema validation, see :manual:`Schema
118+
Validation </core/schema-validation/#schema-validation>` in the MongoDB
119+
Server manual.
120+
| Defaults to ``false``.
121+
122+
* - ``collation``
123+
- | Specifies the kind of language collation to use when sorting
124+
results. For more information, see :manual:`Collation </reference/collation/#std-label-collation>`
125+
in the {+mdb-server+} manual.
126+
127+
* - ``arrayFilters``
128+
- | Specifies which array elements an update applies to if the operation modifies
129+
array fields.
130+
131+
* - ``hint``
132+
- | Sets the index to scan for documents.
133+
For more information, see the :manual:`hint statement </reference/command/update/#std-label-update-command-hint>`
134+
in the {+mdb-server+} manual.
135+
136+
* - ``writeConcern``
137+
- | Sets the write concern for the operation.
138+
For more information, see :manual:`Write Concern </reference/write-concern/>`
139+
in the {+mdb-server+} manual.
140+
141+
* - ``let``
142+
- | Specifies a document with a list of values to improve operation readability.
143+
Values must be constant or closed expressions that don't reference document
144+
fields. For more information, see the :manual:`let statement
145+
</reference/command/update/#std-label-update-let-syntax>` in the
146+
{+mdb-server+} manual.
147+
148+
* - ``comment``
149+
- | A comment to attach to the operation. For more information, see the :manual:`insert command
150+
fields </reference/command/insert/#command-fields>` guide in the
151+
{+mdb-server+} manual.
152+
153+
The following example uses the ``updateMany()`` method to find all documents that
154+
have ``borough`` value of ``'Manhattan'``. It then updates the ``borough`` value
155+
in these documents to ``'Manhattan (north)'``. Because the ``upsert`` option is
156+
set to ``true``, the {+php-library+} inserts a new document if the query filter doesn't
157+
match any existing documents.
158+
159+
.. literalinclude:: /includes/write/update.php
160+
:start-after: start-update-options
161+
:end-before: end-update-options
162+
:language: php
163+
:dedent:
164+
165+
Return Value
166+
~~~~~~~~~~~~
167+
168+
The ``updateOne()`` and ``updateMany()`` methods return an instance of
169+
the ``MongoDB\UpdateResult`` class. This class contains the following
170+
member functions:
171+
172+
.. list-table::
173+
:widths: 30 70
174+
:header-rows: 1
175+
176+
* - Function
177+
- Description
178+
179+
* - ``getMatchedCount()``
180+
- | Returns the number of documents that matched the query filter, regardless of
181+
how many were updated.
182+
183+
* - ``getModifiedCount()``
184+
- | Returns the number of documents modified by the update operation. If an updated
185+
document is identical to the original, it is not included in this
186+
count.
187+
188+
* - ``isAcknowledged()``
189+
- | Returns a boolean indicating whether the write operation was acknowledged.
190+
191+
* - ``getUpsertedCount()``
192+
- | Returns the number of document that were upserted into the database.
193+
194+
* - ``getUpsertedId()``
195+
- | Returns the ID of the document that was upserted in the database, if the driver
196+
performed an upsert.
197+
198+
The following example uses the ``updateMany()`` method to update the ``name`` field
199+
of matching documents from ``'Dunkin' Donuts'`` to ``'Dunkin''``. It calls the
200+
``getModifiedCount()`` member function to print the number of modified documents:
201+
202+
.. io-code-block::
203+
:copyable:
204+
205+
.. input:: /includes/write/update.php
206+
:start-after: start-update-result
207+
:end-before: end-update-result
208+
:language: php
209+
:dedent:
210+
211+
.. output::
212+
:visible: false
213+
214+
Modified documents: 206
215+
216+
Additional Information
217+
----------------------
218+
219+
To learn more about creating query filters, see the :ref:`php-specify-query` guide.
220+
221+
API Documentation
222+
~~~~~~~~~~~~~~~~~
223+
224+
To learn more about any of the methods or types discussed in this
225+
guide, see the following API documentation:
226+
227+
- `MongoDB\\Collection::updateOne() <{+api+}/method/MongoDBCollection-updateOne>`__
228+
- `MongoDB\\Collection::updateMany() <{+api+}/method/MongoDBCollection-updateMany>`__
229+
- `MongoDB\\UpdateResult <{+api+}/class/MongoDBUpdateResult>`__

0 commit comments

Comments
 (0)