Overview
En esta guía, aprenderá a usar la biblioteca PHP de MongoDB para ejecutar una operación de reemplazo en una colección de MongoDB. Una operación de reemplazo funciona de forma diferente a una operación de actualización. Una operación de actualización modifica solo los campos especificados en un documento de destino. Una operación de reemplazo elimina todos los campos del documento de destino y los reemplaza por otros nuevos.
Para reemplazar un documento, utilice el MongoDB\Collection::replaceOne() .
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.
Operación de reemplazo
Puede reemplazar el documento con MongoDB\Collection::replaceOne(). Este método elimina todos los campos excepto el _id del primer documento que coincida con los criterios de búsqueda. A continuación, inserta los campos y valores especificados en el documento.
Parámetros requeridos
El método replaceOne() requiere los siguientes parámetros:
Documento defiltro de consulta, que determina los documentos que se reemplazará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.
Reemplazar documento, que especifica los campos y valores a insertar en el nuevo documento.
Valor de retorno
El método replaceOne() devuelve un objeto MongoDB\UpdateResult. El tipo MongoDB\UpdateResult contiene los siguientes métodos:
Método | 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 the number of documents upserted into the database, if any. |
| Returns the ID of the document that was upserted in the database, if the driver
performed an upsert. |
| Returns a boolean indicating whether the server acknowledged
the write operation. |
Ejemplo
El siguiente ejemplo utiliza el método replaceOne() para reemplazar los campos y valores de un documento en el que el valor del campo name es 'Pizza Town'. Luego, imprime el número de documentos modificados:
$replaceDocument = [ 'name' => 'Mongo\'s Pizza', 'cuisine' => 'Pizza', 'address' => [ 'street' => '123 Pizza St', 'zipCode' => '10003', ], 'borough' => 'Manhattan', ]; $result = $collection->replaceOne(['name' => 'Pizza Town'], $replaceDocument); echo 'Modified documents: ', $result->getModifiedCount();
Modified documents: 1
Importante
Los valores de los campos _id son inmutables. Si el documento de reemplazo especifica un valor para el campo _id, este debe coincidir con el valor _id del documento existente.
Modificar la operación de reemplazo
Puede modificar el comportamiento del método MongoDB\Collection::replaceOne() 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 replace 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 replace operation bypasses document validation. This lets you
replace 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. |
| Specifies the sort order to apply to documents before
performing the replace operation. |
| Specifies the kind of language collation to use when sorting
results. To learn more, see the Collation
section of this page. |
| Gets or sets the index to scan for documents.
For more information, see the hint statement
in the MongoDB Server manual. |
| Specifies the client session to associate with the operation. |
| 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. |
| Attaches a comment to the operation. For more information, see the insert command
fields guide in the
MongoDB Server manual. |
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.
Ejemplo
El siguiente código utiliza el método replaceOne() para buscar el primer documento cuyo campo name tenga el valor 'Food Town' y, a continuación, lo reemplaza por uno nuevo cuyo valor name sea 'Food World'. Dado que la opción upsert está establecida en true, la biblioteca inserta un nuevo documento si el filtro de consulta no coincide con ningún documento existente:
$replaceDocument = [ 'name' => 'Food World', 'cuisine' => 'Mixed', 'address' => [ 'street' => '123 Food St', 'zipCode' => '10003', ], 'borough' => 'Manhattan', ]; $result = $collection->replaceOne( ['name' => 'Food Town'], $replaceDocument, ['upsert' => true], );
Información Adicional
Para obtener más información sobre las operaciones de actualización, consulte la guía Actualizar documentos.
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: