Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

Update Documents

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.

Los ejemplos de esta guía usan 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 tu aplicación PHP, instancie un MongoDB\Client que se conecte a un clúster de Atlas y asigne el siguiente valor a tu variable $collection:

$collection = $client->sample_restaurants->restaurants;

Para saber cómo crear una implementación gratuita de MongoDB y cargar los conjuntos de datos de ejemplo, consulta la guía MongoDB Primeros Pasos.

Puedes 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úsqueda

  • MongoDB\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 query: Especifica qué documentos actualizar. Para obtener más información sobre los filtros de query, consulta la sección Documentos de filtros de query en el manual de MongoDB Server.

  • Actualizar documento: Especifica el operador de actualización, o el tipo de actualización a realizar, así como los campos y valores que se deben cambiar. Para obtener una lista de operadores de actualización y su uso, consulta la Guía de operadores de actualización de campos en el manual de MongoDB Server.

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']],
);

El siguiente ejemplo utiliza el método updateMany() para actualizar todos los documentos que tengan un valor cuisine de 'Pizza'. Después de la actualización, los documentos tienen un cuisine valor de 'Pasta'.

$result = $collection->updateMany(
['cuisine' => 'Pizza'],
['$set' => ['cuisine' => 'Pasta']],
);

Puedes modificar el comportamiento de los métodos updateOne() y updateMany() pasando un arreglo que especifique los valores de opciones como parámetro. La siguiente tabla describe algunas opciones que puedes configurar en el arreglo:

Opción
Descripción

upsert

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.

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 Schema Validation in the MongoDB Server manual.
Defaults to false.

sort

Applies to updateOne() only. Specifies the sort order to apply to documents before performing the update operation.

collation

Specifies the kind of language collation to use when sorting results. To learn more, see the Collation section of this page.

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 hint statement in the MongoDB Server manual.

writeConcern

Sets the write concern for the operation. For more information, see Write Concern in the MongoDB 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 let statement in the MongoDB Server manual.

comment

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 encontrar todos los documentos que tienen borough valor de 'Manhattan'. Luego actualiza el valor borough en estos documentos a 'Manhattan (north)'. Debido a que la opción upsert está configurada en true, la MongoDB PHP librería 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],
);

Para especificar una intercalación para tu operación, pasa un parámetro arreglo $options que establezca la opción collation en el método de la operación. Asigna la opción collation a un arreglo que configure las reglas de intercalación.

La siguiente tabla describe los campos que se pueden configurar para la intercalación:

Campo
Descripción

locale

(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

caseLevel

(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 base
characters and case.

- If strength is 2, the PHP library compares base
characters, 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

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Data Type: string
Default: "off"

strength


Data Type: int
Default: 3

numericOrdering

(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

alternate

(Optional) Specifies whether the library considers whitespace and punctuation as base characters for comparison purposes.

Data Type: string
Default: "non-ignorable"

maxVariable

(Optional) Specifies which characters the library considers ignorable when the alternate field is set to "shifted".

Data Type: string
Default: "punct"

backwards

(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.

Data Type: bool
Default: false

Para obtener más información sobre la intercalación y los posibles valores de cada campo, consulta la entrada Collation en el manual del servidor de MongoDB.

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

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.

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

Para obtener más información sobre cómo crear filtros de consulta, consulte la guía Especificar una consulta.

Para aprender más sobre cualquiera de los métodos o tipos analizados en esta guía, consulta la siguiente documentación de API:

Volver

Acceder a datos desde un cursor

En esta página