Docs Menu
Docs Home
/ /

Reemplazar Documentos

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() .

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.

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.

El método replaceOne() requiere los siguientes parámetros:

El método replaceOne() devuelve un objeto MongoDB\UpdateResult. El tipo MongoDB\UpdateResult contiene los siguientes métodos:

Método
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.

getUpsertedCount()

Returns the number of documents upserted into the database, if any.

getUpsertedId()

Returns the ID of the document that was upserted in the database, if the driver performed an upsert.

isAcknowledged()

Returns a boolean indicating whether the server acknowledged the write operation.

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.

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

upsert

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.

bypassDocumentValidation

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.

sort

Specifies the sort order to apply to documents before performing the replace operation.

collation

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

hint

Gets or sets the index to scan for documents. For more information, see the hint statement in the MongoDB Server manual.

session

Specifies the client session to associate with the operation.

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

Attaches a comment to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.

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

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 para cada campo, consulte la entrada Intercalación en el manual de MongoDB Server.

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

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.

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

Update Documents

En esta página