Menu Docs
Página inicial do Docs
/ / /
Manual da Biblioteca PHP
/

Atualize documentos

Neste guia, você pode aprender como usar a Biblioteca PHP do MongoDB para atualizar documentos em uma coleção MongoDB . Você pode chamar o método MongoDB\Collection::updateOne() para atualizar um único documento ou o método MongoDB\Collection::updateMany() para atualizar vários documentos.

Os exemplos neste guia utilizam a coleção do restaurants no banco de dados de dados do sample_restaurants a partir dos conjuntos de dados de amostra do Atlas. Para acessar essa coleção a partir do seu aplicação PHP , instancie um MongoDB\Client que se conecte a um Atlas cluster e atribua o seguinte valor à sua variável $collection :

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

Para saber como criar um cluster MongoDB Atlas gratuito e carregar os conjuntos de dados de amostra, consulte o guia Iniciar com Atlas .

Você pode executar operações de atualização no MongoDB com os seguintes métodos:

  • MongoDB\Collection::updateOne(), que atualiza o primeiro documento que corresponde aos critérios de pesquisa

  • MongoDB\Collection::updateMany(), que atualiza todos os documentos que correspondem aos critérios de pesquisa

Cada método de atualização exige os seguintes parâmetros:

  • documento de filtro de query : especifica quais documentos atualizar. Para obter mais informações sobre filtros de query, consulte a seção Documentos de filtro de query no manual do MongoDB Server .

  • Atualizar documento: especifica o operador de atualização ou o tipo de atualização a ser executada, e os campos e valores a serem alterados. Para obter uma lista de operadores de atualização e seu uso, consulte o guia Operadores de atualização de campo no manual do MongoDB Server .

O exemplo seguinte utiliza o método updateOne() para atualizar o valor name de um documento na coleção restaurants de 'Bagels N Buns' para '2 Bagels 2 Buns':

$result = $collection->updateOne(
['name' => 'Bagels N Buns'],
['$set' => ['name' => '2 Bagels 2 Buns']],
);

O exemplo seguinte utiliza o método updateMany() para atualizar todos os documentos que têm um valor cuisine de 'Pizza'. Após a atualização, os documentos têm um valor cuisine de 'Pasta'.

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

Você pode modificar o comportamento dos métodos updateOne() e updateMany() passando uma array que especifique valores de opção como um parâmetro. A tabela a seguir descreve algumas opções que você pode definir na array:

Opção
Descrição

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.

O exemplo a seguir usa o método updateMany() para localizar todos os documentos que têm borough valor de 'Manhattan'. Em seguida, ele atualiza o valor borough nesses documentos para 'Manhattan (north)'. Como a opção upsert está definida como true, a Biblioteca PHP do MongoDB insere um novo documento se o filtro de query não corresponder a nenhum documento existente.

$result = $collection->updateMany(
['borough' => 'Manhattan'],
['$set' => ['borough' => 'Manhattan (north)']],
['upsert' => true],
);

Para especificar um agrupamento para sua operação, passe um parâmetro de array $options que defina a opção collation para o método de operação. Atribua a opção collation a uma array que configure as regras de agrupamento.

A tabela a seguir descreve os campos que você pode definir para configurar o agrupamento:

Campo
Descrição

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 saber mais sobre agrupamento e os possíveis valores para cada campo, consulte a entrada de Agrupamento no manual do MongoDB Server .

Os métodos updateOne() e updateMany() retornam uma instância da classe MongoDB\UpdateResult . Esta classe contém as seguintes funções de membro:

Função
Descrição

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 server acknowledged the write operation.

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.

O exemplo a seguir usa o método updateMany() para atualizar o campo name dos documentos correspondentes de 'Dunkin' Donuts' para 'Dunkin''. Ele chama a função de membro getModifiedCount() para imprimir o número de documentos modificados:

$result = $collection->updateMany(
['name' => 'Dunkin\' Donuts'],
['$set' => ['name' => 'Dunkin\'']],
);
echo 'Modified documents: ', $result->getModifiedCount();
Modified documents: 206

Para saber mais sobre como criar filtros de queries, consulte o guia Especifique uma consulta.

Para saber mais sobre qualquer um dos métodos ou tipos discutidos neste guia, consulte a seguinte documentação da API:

Voltar

Acessar dados de um cursor

Nesta página