Definição
$replaceOneSubstitui a primeira instância de uma string de pesquisa ou padrão regex em uma string de input por uma string de substituição.
If no occurrences are found,
$replaceOneevaluates to the input string.$replaceOnediferencia maiúsculas de minúsculas e diacríticos e ignora qualquer agrupamento presente em uma collection.
Sintaxe
The $replaceOne operator has the following operator expression syntax:
{ $replaceOne: { input: <expression>, find: <expression>, replacement: <expression> } }
Campos do operador
Campo | Descrição |
|---|---|
The string on which you wish to apply the find. Can be any valid expression that resolves to a string or a | |
The string to search for within the given input. Can be any valid expression that resolves to a string, a regex, or a | |
The string to use to replace the first matched instance of find in input. Can be any valid expression that resolves to a string or a |
Comportamento
If no occurrences of find are found in input, $replaceOne evaluates to the input string.
The input, find, and replacement expressions must evaluate to one of the following output types:
Um string
nullA regex for find operations
Otherwise, $replaceOne fails with an error.
$replaceOne e valores nulos
If input or find refer to a field that is missing, they return null.
If any one of input, find, or replacement evaluates to a null, the entire $replaceOne expression evaluates to null:
Exemplo | Resultado |
|---|---|
|
|
|
|
|
|
$replaceOne e Agrupamento
a correspondência de strings para expressões $replaceOne sempre faz distinção entre maiúsculas e minúsculas e diacríticos. Qualquer agrupamento configurado é ignorado ao realizar comparações de strings com $replaceOne.
Por exemplo, crie uma collection de amostras com força de agrupamento 1:
db.createCollection( "restaurants", { collation: { locale: "fr", strength: 1 } } )
A força de um agrupamento de 1 compara apenas o caractere base e ignora outras diferenças, como letras maiúsculas, letras minúsculas e diacríticos.
Em seguida, insira documentos de exemplo :
db.restaurants.insertMany( [ { _id: 1, name: "cafe" }, { _id: 2, name: "Cafe" }, { _id: 3, name: "café" } ] )
The following $replaceOne operation tries to find and replace the first instance of "Cafe" in the name field:
db.restaurants.aggregate( [ { $addFields: { resultObject: { $replaceOne: { input: "$name", find: "Cafe", replacement: "CAFE" } } } } ] )
{ "_id" : 1, "name" : "cafe", "resultObject" : "cafe" } { "_id" : 2, "name" : "Cafe", "resultObject" : "CAFE" } { "_id" : 3, "name" : "café", "resultObject" : "café" }
Because $replaceOne ignores the collation configured for this collection, the operation only matches the instance of "Cafe" in document 2.
Os operadores que respeitam o agrupamento, como $match, corresponderiam a todos os três documentos ao realizar uma comparação de strings de "Cafe" devido à força de agrupamento dessa collection de 1.
$replaceOne e normalização Unicode
The $replaceOne aggregation expression does not perform any unicode normalization. This means that string matching for all $replaceOne expressions will consider the number of code points used to represent a character in unicode when attempting a match.
Por exemplo, o caractere é pode ser representado em unicode usando um ou dois pontos de código:
Unicode | Aparece como | Pontos de código |
|---|---|---|
|
| 1 ( |
|
| 2 ( |
Using $replaceOne with a find string where the character é is represented in unicode with one code point will not match any instance of é that uses two code points in the input string.
The following table shows whether a match occurs for a find string of "café" when compared to input strings where é is represented by either one code point or two. The find string in this example uses one code point to represent the é character:
Exemplo | corresponder |
|---|---|
| sim |
| no |
Because $replaceOne does not perform any unicode normalization, only the first string comparison matches, where both the find and input strings use one code point to represent é.
Exemplos
Cria uma collection inventory com os seguintes documentos:
db.inventory.insertMany( [ { _id: 1, item: "blue paint" }, { _id: 2, item: "blue and green paint" }, { _id: 3, item: "blue paint with blue paintbrush" }, { _id: 4, item: "blue paint with green paintbrush" }, ] )
Substituir usando uma string
O exemplo a seguir substitui a primeira instância de "blue paint" no campo item por "red paint":
db.inventory.aggregate([ { $project: { item: { $replaceOne: { input: "$item", find: "blue paint", replacement: "red paint" } } } } ])
A operação retorna os seguintes resultados:
{ _id: 1, item: "red paint" } { _id: 2, item: "blue and green paint" } { _id: 3, item: "red paint with blue paintbrush" } { _id: 4, item: "red paint with green paintbrush" }
Observe que, com o documento 3, somente a primeira instância correspondente de "blue print" é substituída.
Substitua usando Regex
O exemplo a seguir substitui a primeira instância de "blue" como uma palavra inteira no campo item por "navy":
db.inventory.aggregate([ { $project: { item: { $replaceOne: { input: "$item", find: \\bblue\\b, replacement: "navy" } } } } ]);
A operação retorna os seguintes resultados:
{ _id: 1, item: "navy paint" } { _id: 2, item: "navy and green paint" } { _id: 3, item: "navy paint with blue paintbrush" } { _id: 4, item: "navy paint with green paintbrush" }
Observe que, com o document 3, somente a primeira instância correspondente de "blue" é substituída.