Overview
In this guide, you can learn how to use the MongoDB 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 sample datasets. 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:
$collection = $client->sample_restaurants->restaurants;
To learn how to create a free MongoDB deployment and load the sample datasets, see the MongoDB Get 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 criteriaMongoDB\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 Query Filter Documents section in the MongoDB 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 Field Update Operators guide in the MongoDB Server manual.
Update One Document
The following example uses the updateOne() method to update the name value of a document in the restaurants collection from 'Bagels N Buns' to '2 Bagels 2 Buns':
$result = $collection->updateOne( ['name' => 'Bagels N Buns'], ['$set' => ['name' => '2 Bagels 2 Buns']], );
Update Many Documents
The following example uses the updateMany() method to update all documents that have a cuisine value of 'Pizza'. After the update, the documents have a cuisine value of 'Pasta'.
$result = $collection->updateMany( ['cuisine' => 'Pizza'], ['$set' => ['cuisine' => 'Pasta']], );
Customize the Update Operation
You can modify the behavior of the updateOne() and updateMany() methods by passing an array that specifies option values as a parameter. The following table describes some options you can set in the array:
Option | Description |
|---|---|
| Specifies whether the update operation performs an upsert operation if no
documents match the query filter. For more information, see the upsert
statement
in the MongoDB Server manual. |
| 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 Schema
Validation in the MongoDB
Server manual. |
| Applies to |
| Specifies the kind of language collation to use when sorting results. To learn more, see the Collation section of this page. |
| Specifies which array elements an update applies to if the operation modifies array fields. |
| Sets the index to scan for documents. For more information, see the hint statement in the MongoDB Server manual. |
| Sets the write concern for the operation. For more information, see Write Concern in the MongoDB Server manual. |
| 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 let statement in the MongoDB Server manual. |
| A comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB Server manual. |
The following example uses the updateMany() method to find all documents that 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 MongoDB PHP Library inserts a new document if the query filter doesn't match any existing documents.
$result = $collection->updateMany( ['borough' => 'Manhattan'], ['$set' => ['borough' => 'Manhattan (north)']], ['upsert' => true], );
Collation
To specify a collation for your operation, pass an $options array parameter that sets the collation option to the operation method. Assign the collation option to an array that configures the collation rules.
The following table describes the fields you can set to configure the collation:
Field | Description |
|---|---|
| (Required) Specifies the International Components for Unicode (ICU) locale. For a
list of supported locales, see Collation Locales and Default Parameters
in the MongoDB Server manual. |
| (Optional) Specifies whether to include case comparison. |
| (Optional) Specifies the sort order of case differences during tertiary
level comparisons. |
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. |
| (Optional) Specifies whether the driver compares numeric strings as numbers. |
| (Optional) Specifies whether the library considers whitespace and punctuation as base
characters for comparison purposes. |
| (Optional) Specifies which characters the library considers ignorable when
the |
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. |
To learn more about collation and the possible values for each field, see the Collation entry in the MongoDB Server manual.
Return Value
The updateOne() and updateMany() methods return an instance of the MongoDB\UpdateResult class. This class contains the following member functions:
Function | Description |
|---|---|
| Returns the number of documents that matched the query filter, regardless of how many were updated. |
| 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. |
| Returns a boolean indicating whether the server acknowledged the write operation. |
| Returns the number of document that were upserted into the database. |
| 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 of matching documents from 'Dunkin' Donuts' to 'Dunkin''. It calls the getModifiedCount() member function to print the number of modified documents:
$result = $collection->updateMany( ['name' => 'Dunkin\' Donuts'], ['$set' => ['name' => 'Dunkin\'']], ); echo 'Modified documents: ', $result->getModifiedCount();
Modified documents: 206
Update Builder
You can use the MongoDB\Builder\Update class to construct update documents with the support of IDE code completion and PHP type checking. The Update class provides factory methods that correspond to MongoDB update operators such as $set, $inc, and $unset.
To use the update builder, import the following classes into your application:
use MongoDB\Builder\Query; use MongoDB\Builder\Update;
The following example uses the Update::set() factory method to update the name field to '2 Bagels 2 Buns' in the first matching document with a name value of 'Bagels N Buns' in the restaurants collection:
$result = $collection->updateOne( Query::query(name: Query::eq('Bagels N Buns')), Update::set(name: '2 Bagels 2 Buns'), );
To apply multiple update operators in a single operation, pass the operators to the MongoDB\Builder\Update constructor. The following example combines Update::set() and Update::unset() to set the cuisine field to Pasta and remove the grades field from all documents with a cuisine value of 'Pizza':
$result = $collection->updateMany( Query::query(cuisine: Query::eq('Pizza')), new Update( Update::set(cuisine: 'Pasta'), Update::unset('grades'), ), );
To learn more about the builder classes and view more examples, see the Operations with Builders guide.
Additional Information
To learn more about creating query filters, see the Specify a Query guide.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: