Skip to content

DOCSP-41968: Update documents #118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion snooty.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,4 @@ php-library = "MongoDB PHP Library"
php-library = "MongoDB PHP Library"
driver-short = "PHP library"
mdb-server = "MongoDB Server"
driver-short = "PHP library"
api = "https://www.mongodb.com/docs/php-library/current/reference"
45 changes: 45 additions & 0 deletions source/includes/write/update.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

require 'vendor/autoload.php';

$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
$client = new MongoDB\Client($uri);

// start-db-coll
$collection = $client->sample_restaurants->restaurants;
// end-db-coll

// Updates the "name" value of a document from "Bagels N Buns" to "2 Bagels 2 Buns"
// start-update-one
$result = $collection->updateOne(
['name' => 'Bagels N Buns'],
['$set' => ['name' => '2 Bagels 2 Buns']]
);
// end-update-one

// Updates the "cuisine" value of documents from "Pizza" to "Pasta"
// start-update-many
$result = $collection->updateMany(
['cuisine' => 'Pizza'],
['$set' => ['cuisine' => 'Pasta']]
);
// end-update-many

// Updates the "borough" value of matching documents and inserts a document if none match
// start-update-options
$result = $collection->updateMany(
['borough' => 'Manhattan'],
['$set' => ['borough' => 'Manhattan (north)']],
['upsert' => true]
);
// end-update-options

// Updates the "name" value of matching documents and prints the number of updates
// start-update-result
$result = $collection->updateMany(
['name' => 'Dunkin\' Donuts'],
['$set' => ['name' => 'Dunkin\'']]
);
echo 'Modified documents: ' . $result->getModifiedCount();
// end-update-result

1 change: 1 addition & 0 deletions source/index.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ MongoDB PHP Library

Get Started </get-started>
/read
/write
/tutorial
/upgrade
/reference
Expand Down
11 changes: 11 additions & 0 deletions source/write.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.. _php-write:

=====================
Write Data to MongoDB
=====================

.. toctree::
:titlesonly:
:maxdepth: 1

/write/update
229 changes: 229 additions & 0 deletions source/write/update.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
.. _php-write-update:

================
Update Documents
================

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: modify, change, bulk, code example

Overview
--------

In this guide, you can learn how to use the {+php-library+} to update
documents in a MongoDB collection. You can call the ``MongoDB\Collection::updateOne()``
method to update a single document or the ``MongoDB\Collection::updateMany()``
method to update multiple documents.

Sample Data
~~~~~~~~~~~

The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster
and assign the following value to your ``collection`` variable:

.. literalinclude:: /includes/write/update.php
:language: php
:dedent:
:start-after: start-db-coll
:end-before: end-db-coll

To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
:atlas:`Get Started with Atlas </getting-started>` guide.

Update Operations
-----------------

You can perform update operations in MongoDB by using the following methods:

- ``MongoDB\Collection::updateOne()``, which updates *the first document* that
matches the search criteria
- ``MongoDB\Collection::updateMany()``, which updates *all documents* that match
the search criteria

Each update method requires the following parameters:

- **Query filter** document: Specifies which documents to update. For
more information about query filters, see the
:manual:`Query Filter Documents section </core/document/#query-filter-documents>` in
the {+mdb-server+} manual.

- **Update** document: Specifies the **update operator**, or the kind of update to
perform, and the fields and values to change. For a list of update operators
and their usage, see the :manual:`Field Update Operators guide
</reference/operator/update-field/>` in the {+mdb-server+} manual.

Update One Document
~~~~~~~~~~~~~~~~~~~

The following example uses the ``updateOne()`` method to update the ``name``
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: Do we need to refer to this with the full MongoDB\Collection::updateOne() name every time? There's a few other occurrences in this PR where we don't use the long method name as well.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've been using the full name for first mentions in each top-level section, then the shortened name for future mentions in that section and in its subsections.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense to me and looks like this page adheres to that rule.

value of a document in the ``restaurants`` collection from ``'Bagels N Buns'``
to ``'2 Bagels 2 Buns'``:
Comment on lines +71 to +72
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I chuckled


.. literalinclude:: /includes/write/update.php
:start-after: start-update-one
:end-before: end-update-one
:language: php
:dedent:

Update Many Documents
~~~~~~~~~~~~~~~~~~~~~

The following example uses the ``updateMany()`` method to update all documents
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same question re: long/short name

that have a ``cuisine`` value of ``'Pizza'``. After the update, the documents have
a ``cuisine`` value of ``'Pasta'``.

.. literalinclude:: /includes/write/update.php
:start-after: start-update-many
:end-before: end-update-many
:language: php
:dedent:

Customize the Update Operation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can modify the behavior of the ``updateOne()`` and ``updateMany()`` methods by
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same question re: long/short name

passing an array that specifies option values as a parameter. The following table
describes some options you can set in the array:

.. list-table::
:widths: 30 70
:header-rows: 1

* - Option
- Description

* - ``upsert``
- | Specifies whether the update operation performs an upsert operation if no
documents match the query filter. For more information, see the :manual:`upsert
statement </reference/command/update/#std-label-update-command-upsert>`
in the {+mdb-server+} manual.
| Defaults to ``false``.

* - ``bypassDocumentValidation``
- | Specifies whether the update operation bypasses document validation. This lets you
update documents that don't meet the schema validation requirements, if any
exist. For more information about schema validation, see :manual:`Schema
Validation </core/schema-validation/#schema-validation>` in the MongoDB
Server manual.
| Defaults to ``false``.

* - ``collation``
- | Specifies the kind of language collation to use when sorting
results. For more information, see :manual:`Collation </reference/collation/#std-label-collation>`
in the {+mdb-server+} manual.

* - ``arrayFilters``
- | Specifies which array elements an update applies to if the operation modifies
array fields.

* - ``hint``
- | Sets the index to scan for documents.
For more information, see the :manual:`hint statement </reference/command/update/#std-label-update-command-hint>`
in the {+mdb-server+} manual.

* - ``writeConcern``
- | Sets the write concern for the operation.
For more information, see :manual:`Write Concern </reference/write-concern/>`
in the {+mdb-server+} manual.

* - ``let``
- | Specifies a document with a list of values to improve operation readability.
Values must be constant or closed expressions that don't reference document
fields. For more information, see the :manual:`let statement
</reference/command/update/#std-label-update-let-syntax>` in the
{+mdb-server+} manual.

* - ``comment``
- | A comment to attach to the operation. For more information, see the :manual:`insert command
fields </reference/command/insert/#command-fields>` guide in the
{+mdb-server+} manual.

The following example uses the ``updateMany()`` method to find all documents that
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same question re: long/short name

have ``borough`` value of ``'Manhattan'``. It then updates the ``borough`` value
in these documents to ``'Manhattan (north)'``. Because the ``upsert`` option is
set to ``true``, the {+php-library+} inserts a new document if the query filter doesn't
match any existing documents.

.. literalinclude:: /includes/write/update.php
:start-after: start-update-options
:end-before: end-update-options
:language: php
:dedent:

Return Value
~~~~~~~~~~~~

The ``updateOne()`` and ``updateMany()`` methods return an instance of
the ``MongoDB\UpdateResult`` class. This class contains the following
member functions:

.. list-table::
:widths: 30 70
:header-rows: 1

* - Function
- Description

* - ``getMatchedCount()``
- | Returns the number of documents that matched the query filter, regardless of
how many were updated.

* - ``getModifiedCount()``
- | Returns the number of documents modified by the update operation. If an updated
document is identical to the original, it is not included in this
count.

* - ``isAcknowledged()``
- | Returns a boolean indicating whether the write operation was acknowledged.

* - ``getUpsertedCount()``
- | Returns the number of document that were upserted into the database.

* - ``getUpsertedId()``
- | Returns the ID of the document that was upserted in the database, if the driver
performed an upsert.

The following example uses the ``updateMany()`` method to update the ``name`` field
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same question re: long/short name

of matching documents from ``'Dunkin' Donuts'`` to ``'Dunkin''``. It calls the
``getModifiedCount()`` member function to print the number of modified documents:

.. io-code-block::
:copyable:

.. input:: /includes/write/update.php
:start-after: start-update-result
:end-before: end-update-result
:language: php
:dedent:

.. output::
:visible: false

Modified documents: 206

Additional Information
----------------------

To learn more about creating query filters, see the :ref:`php-specify-query` guide.

API Documentation
~~~~~~~~~~~~~~~~~

To learn more about any of the methods or types discussed in this
guide, see the following API documentation:

- `MongoDB\\Collection::updateOne() <{+api+}/method/MongoDBCollection-updateOne>`__
- `MongoDB\\Collection::updateMany() <{+api+}/method/MongoDBCollection-updateMany>`__
- `MongoDB\\UpdateResult <{+api+}/class/MongoDBUpdateResult>`__
Loading