Overview
En esta guía, aprenderá a usar la biblioteca PHP de MongoDB para actualizar documentos en una colección de MongoDB. Puede llamar a MongoDB\Collection::updateOne()
método para actualizar un solo documento o el método MongoDB\Collection::updateMany() para actualizar varios documentos.
Datos de muestra
Los ejemplos de esta guía utilizan la colección restaurants en la base de datos sample_restaurants de la Conjuntos de datos de muestra de Atlas. Para acceder a esta colección desde su aplicación PHP, cree MongoDB\Client una instancia de que se conecte a un clúster de Atlas y asigne el siguiente valor a su $collection variable:
$collection = $client->sample_restaurants->restaurants;
Para aprender cómo crear una implementación gratuita de MongoDB y cargar los conjuntos de datos de muestra, consulte la guía de introducción a MongoDB.
Operaciones de actualizar
Puede realizar operaciones de actualización en MongoDB utilizando los siguientes métodos:
MongoDB\Collection::updateOne(), que actualiza el primer documento que coincide con los criterios de búsquedaMongoDB\Collection::updateMany(), que actualiza todos los documentos que coinciden con los criterios de búsqueda
Cada método de actualización requiere los siguientes parámetros:
Documento de filtro de consulta: Especifica los documentos que se actualizarán. Para obtener más información sobre los filtros de consulta, consulte la sección "Documentos de filtro de consulta" en el manual de MongoDB Server.
Actualizar documento: Especifica el operador de actualización, o el tipo de actualización que se realizará, y los campos y valores que se modificarán. Para obtener una lista de operadores de actualización y su uso, consulte la guía "Operadores de actualización de campos" en el manual de MongoDB Server.
Actualizar un documento
El siguiente ejemplo utiliza el método updateOne() para actualizar el valor name de un documento en la colección restaurants de 'Bagels N Buns' a '2 Bagels 2 Buns':
$result = $collection->updateOne( ['name' => 'Bagels N Buns'], ['$set' => ['name' => '2 Bagels 2 Buns']], );
Actualizar muchos documentos
El siguiente ejemplo utiliza el método updateMany() para actualizar todos los documentos cuyo valor cuisine es 'Pizza'. Tras la actualización, los documentos tienen un valor cuisine de 'Pasta'.
$result = $collection->updateMany( ['cuisine' => 'Pizza'], ['$set' => ['cuisine' => 'Pasta']], );
Personalizar la operación de actualización
Puede modificar el comportamiento de los métodos updateOne() y updateMany() pasando una matriz que especifique valores de opción como parámetro. La siguiente tabla describe algunas opciones que puede configurar en la matriz:
Opción | Descripción |
|---|---|
| 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. |
El siguiente ejemplo utiliza el método updateMany() para buscar todos los documentos cuyo valor borough es 'Manhattan'. A continuación, actualiza el valor borough de estos documentos a 'Manhattan (north)'. Dado que la opción upsert está establecida en true, la biblioteca PHP de MongoDB inserta un nuevo documento si el filtro de consulta no coincide con ningún documento existente.
$result = $collection->updateMany( ['borough' => 'Manhattan'], ['$set' => ['borough' => 'Manhattan (north)']], ['upsert' => true], );
Intercalación
Para especificar una intercalación para su operación, pase un parámetro de matriz $options que establezca la opción collation en el método de la operación. Asigne la opción collation a una matriz que configure las reglas de intercalación.
La siguiente tabla describe los campos que se pueden configurar para la intercalación:
Campo | Descripción |
|---|---|
| (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: boolDefault: false |
| (Optional) Specifies the sort order of case differences during tertiary
level comparisons. Data Type: stringDefault: "off" |
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. Data Type: intDefault: 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: boolDefault: false |
| (Optional) Specifies whether the library considers whitespace and punctuation as base
characters for comparison purposes. Data Type: stringDefault: "non-ignorable" |
| (Optional) Specifies which characters the library considers ignorable when
the alternate field is set to "shifted".Data Type: stringDefault: "punct" |
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. Data Type: boolDefault: false |
Para obtener más información sobre la intercalación y los posibles valores para cada campo, consulte la entrada Intercalación en el manual de MongoDB Server.
Valor de retorno
Los métodos updateOne() y updateMany() devuelven una instancia de la clase MongoDB\UpdateResult. Esta clase contiene las siguientes funciones miembro:
Función | Descripción |
|---|---|
| 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. |
El siguiente ejemplo utiliza el método updateMany() para actualizar el campo name de los documentos coincidentes de 'Dunkin' Donuts' a 'Dunkin''. Llama a la función miembro getModifiedCount() para imprimir el número de documentos modificados:
$result = $collection->updateMany( ['name' => 'Dunkin\' Donuts'], ['$set' => ['name' => 'Dunkin\'']], ); echo 'Modified documents: ', $result->getModifiedCount();
Modified documents: 206
Información Adicional
Para obtener más información sobre cómo crear filtros de consulta, consulte la guía Especificar una consulta.
Documentación de la API
Para aprender más sobre cualquiera de los métodos o tipos analizados en esta guía, consulta la siguiente documentación de API: