Update Documents
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 Atlas cluster and load the sample datasets, see the Get Started with Atlas 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. Defaults to false . |
| 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. Defaults to false . |
| Applies to updateOne() only. Specifies the sort order to
apply to documents before performing the update operation. |
| 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. Data Type: string |
| (Optional) Specifies whether to include case comparison. When set to true , the comparison behavior depends on the value of
the strength field:- If strength is 1 , the PHP library compares basecharacters and case. - If strength is 2 , the PHP library compares basecharacters, diacritics, other secondary differences, and case. - If strength is any other value, this field is ignored.When set to false , the PHP library doesn't include case comparison at
strength level 1 or 2 .Data Type: bool Default: false |
| (Optional) Specifies the sort order of case differences during tertiary
level comparisons. Data Type: string Default: "off" |
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. Data Type: int Default: 3 |
| (Optional) Specifies whether the driver compares numeric strings as numbers. If set to true , the PHP library compares numeric strings as numbers.
For example, when comparing the strings "10" and "2", the library uses the
strings' numeric values and treats "10" as greater than "2".If set to false , the PHP library compares numeric strings
as strings. For example, when comparing the strings "10" and "2", the library
compares one character at a time and treats "10" as less than "2".For more information, see Collation Restrictions
in the MongoDB Server manual. Data Type: bool Default: false |
| (Optional) Specifies whether the library considers whitespace and punctuation as base
characters for comparison purposes. Data Type: string Default: "non-ignorable" |
| (Optional) Specifies which characters the library considers ignorable when
the alternate field is set to "shifted" .Data Type: string Default: "punct" |
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. Data Type: bool Default: false |
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 write operation was acknowledged. |
| 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
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: