Definição
$replaceAllSubstitui todas as instâncias de uma string de pesquisa em uma string de entrada por uma string de substituição.
$replaceAlldiferencia maiúsculas de minúsculas e diacríticos e ignora qualquer agrupamento presente em uma collection.
Sintaxe
The $replaceAll operator has the following operator expression syntax:
{ $replaceAll: { 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 or a | |
The string to use to replace all matched instances of find in input. Can be any valid expression that resolves to a string or a |
Comportamento
The input, find, and replacement expressions must evaluate to a string or a null, or $replaceAll fails with an error.
$replaceAll 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 $replaceAll expression evaluates to null:
Exemplo | Resultado |
|---|---|
|
|
|
|
|
|
$replaceAll e Agrupamento
a correspondência de strings para expressões $replaceAll sempre faz distinção entre maiúsculas e minúsculas e diacríticos. Qualquer agrupamento configurado é ignorado ao realizar comparações de strings com $replaceAll.
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é" } ] )
A seguinte operação do $replaceAll tenta localizar e substituir todas as instâncias do "Cafe" no campo name :
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 $replaceAll ignores the collation configured for this collection, the operation only matches the instance of "Cafe" in document 2:
{ _id: 1, name: "cafe", resultObject: "cafe" } { _id: 2, name: "Cafe", resultObject: "CAFE" } { _id: 3, name: "café", resultObject: "café" }
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.
$replaceAll e normalização Unicode
The $replaceAll aggregation expression does not perform any unicode normalization. This means that string matching for all $replaceAll 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 $replaceAll 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 $replaceAll 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 é.
Exemplo
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" }, ] )
O exemplo a seguir substitui cada instância de "tinta azul" no campo item por "tinta vermelha":
db.inventory.aggregate([ { $project: { item: { $replaceAll: { 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 red paintbrush" } { _id: 4, item: "red paint with green paintbrush" }