Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /

Reemplazar Documentos

En esta guía, puedes aprender a utilizar la Librería PHP de MongoDB para ejecutar una operación de reemplazo en una colección de MongoDB. Una operación de reemplazo se comporta de manera 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 remueve todos los campos en el documento de destino y los reemplaza por otros nuevos.

Para reemplazar un documento, use el MongoDB\Collection::replaceOne() .

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 una operación de reemplazo utilizando MongoDB\Collection::replaceOne(). Este método remueve todos los campos excepto el campo _id del primer documento que coincide con los criterios de búsqueda. Luego, inserta los campos y valores que especifiques en el documento.

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

  • filtro de query documento, que determina los documentos a reemplazar. 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.

  • Reemplaza el documento, que especifica los campos y valores que se deben insertar en el nuevo documento.

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 tu documento de reemplazo especifica un valor para el campo _id, este debe coincidir con el valor _id del documento existente.

Puedes modificar el comportamiento del método MongoDB\Collection::replaceOne() pasando un arreglo que especifique 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 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 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.

El siguiente código utiliza el método replaceOne() para encontrar el primer documento en el que el campo name tenga el valor 'Food Town', y luego reemplaza este documento con uno nuevo en el que el valor name sea 'Food World'. Debido a que la opción upsert está configurada en true, la librería inserta un nuevo documento si el filtro de query 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 query, se puede consultar la Especificar una query.

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