Para agentes de IA: um índice de documentação está disponível em https://www.mongodb.com/pt-br/docs/llms.txt — as versões de markdown de todas as páginas estão disponíveis anexando .md a qualquer caminho de URL.
Menu Docs

$regexFind (operador de expressão )

$regexFind

Fornece capacidade da corresponder padrões de expressões regulares (regex) em expressões de aggregation. Se for encontrada uma correspondência, retornará um documento que contém informações sobre a primeira correspondência. Se uma correspondência não for encontrada, retornará nulo.

The $regexFind operator has the following syntax:

{ $regexFind: { input: <expression> , regex: <expression>, options: <expression> } }
Campo
Descrição

A string na qual você deseja aplicar o padrão regex. Pode ser uma string ou qualquer expressão válida que resolva para uma string.

O padrão regex a aplicar. Pode ser qualquer expressão válida que produza uma string ou padrão regex /<pattern>/. Ao utilizar o regex /<pattern>/, você também pode especificar as opções regex i e m (mas não as opções s ou x):

  • "pattern"

  • /<pattern>/

  • /<pattern>/<options>

Como alternativa, você também pode especificar as opções de regex com o campo de opções. Para especificar as s x opções ou, você deve usar o campo de opções.

Não é permitido especificar opções no campo regex e options.

Opcional. Os <options> a seguir estão disponíveis para uso com expressões regulares.

Não é permitido especificar opções no campo regex e options.

  • i: Insensibilidade a maiúsculas e minúsculas para combinar maiúsculas e minúsculas. Você pode especificar a opção no campo options ou como parte do campo regex.

  • m: Para padrões que incluem âncoras (ou seja, ^ para o início, $ para o final), corresponde ao início ou ao final de cada linha para strings com valores de várias linhas. Sem essa opção, essas âncoras coincidem no início ou no final da string.

    Se o padrão não contiver âncoras ou se o valor da string não tiver caracteres de nova linha (por exemplo, \n), a opção m não tem efeito.

  • x: Capacidade "estendida" para ignorar todos os caracteres de espaço em branco no padrão, a menos que de escape ou incluído em uma classe de caracteres.

    Além disso, ele ignora caracteres intermediários e inclui um caractere de cerquilha (#) não evitado e a próxima nova linha, para que você possa incluir comentários em padrões complicados. Isso se aplica apenas a caracteres de dados. Caracteres de espaço em branco nunca podem aparecer em sequências de caracteres especiais em um padrão.

    A opção x não afeta o manuseio do caractere TP (código 11).

    Você pode especificar a opção somente no campo options.

  • s: Permite que o caractere ponto (.) corresponda a todos os caracteres, incluindo caracteres de nova linha.

    Você pode especificar a opção somente no campo options.

Se o operador não encontrar uma correspondência, o resultado dele será um null.

Se o operador encontrar uma correspondência, o resultado dele será um documento contendo:

  • a primeira string correspondente na entrada,

  • o índice ponto de código (não índice de bytes) da string correspondente na entrada, e

  • An array of the strings that corresponds to the groups captured by the matching string. Capturing groups are specified with unescaped parenthesis () in the regex pattern.

{ "match" : <string>, "idx" : <num>, "captures" : <array of strings> }

A partir da versão 6.1, O MongoDB usa a biblioteca PCRE2 (Perl Compatible Regular Expressions) para implementar a correspondência regular de padrões de expressão . Para saber mais sobre PCRE2, consulte a Documentação de PCRE.

a correspondência de strings para $regexFind sempre diferencia maiúsculas, minúsculas e diacríticos. $regexFind ignora o agrupamento especificado para a coleção, db.collection.aggregate() e o índice, se utilizado.

Por exemplo, crie uma collection com força de agrupamento 1, o que significa que o agrupamento compara apenas caracteres básicos e ignora diferenças como letras maiúsculas, letras minúsculas e diacríticos:

db.createCollection( "restaurants", { collation: { locale: "fr", strength: 1 } } )

Insira os seguintes documentos:

db.restaurants.insertMany( [
{ _id: 1, category: "café", status: "Open" },
{ _id: 2, category: "cafe", status: "open" },
{ _id: 3, category: "cafE", status: "open" }
] )

O seguinte usa o agrupamento da coleção para realizar uma correspondência insensível a maiúsculas e minúsculas e insensível a diacríticos:

db.restaurants.aggregate( [ { $match: { category: "cafe" } } ] )
[
{ _id: 1, category: 'café', status: 'Open' },
{ _id: 2, category: 'cafe', status: 'open' },
{ _id: 3, category: 'cafE', status: 'open' }
]

No entanto, $regexFind ignora o agrupamento. Os exemplos de correspondência de padrão de expressão regular a seguir diferenciam maiúsculas de minúsculas e diacríticos:

db.restaurants.aggregate( [
{
$addFields: {
resultObject: { $regexFind: { input: "$category", regex: /cafe/ } }
}
}
] )
db.restaurants.aggregate( [
{
$addFields: {
resultObject: { $regexFind: { input: "$category", regex: /cafe/ } }
}
}
],
{ collation: { locale: "fr", strength: 1 } } // Ignored in the $regexFind
)

Ambas as operações retornam o seguinte:

{ "_id" : 1, "category" : "café", "resultObject" : null }
{ "_id" : 2, "category" : "cafe", "resultObject" : { "match" : "cafe", "idx" : 0, "captures" : [ ] } }
{ "_id" : 3, "category" : "cafE", "resultObject" : null }

Como a query ignora o agrupamento, ela exige uma correspondência exata na string category (incluindo maiúsculas e minúsculas e acentos), o que significa que somente o documento _id: 2 corresponde.

To perform a case-insensitive regex pattern matching, use the i Option instead. See i Option for an example.

If your regex pattern contains capture groups and the pattern finds a match in the input, the captures array in the results corresponds to the groups captured by the matching string. Capture groups are specified with unescaped parentheses () in the regex pattern. The length of the captures array equals the number of capture groups in the pattern and the order of the array matches the order in which the capture groups appear.

Crie uma coleção de amostra denominada contacts com os seguintes documentos:

db.contacts.insertMany([
{ "_id": 1, "fname": "Carol", "lname": "Smith", "phone": "718-555-0113" },
{ "_id": 2, "fname": "Daryl", "lname": "Doe", "phone": "212-555-8832" },
{ "_id": 3, "fname": "Polly", "lname": "Andrews", "phone": "208-555-1932" },
{ "_id": 4, "fname": "Colleen", "lname": "Duncan", "phone": "775-555-0187" },
{ "_id": 5, "fname": "Luna", "lname": "Clarke", "phone": "917-555-4414" }
])

The following pipeline applies the regex pattern /(C(ar)*)ol/ to the fname field:

db.contacts.aggregate([
{
$project: {
returnObject: {
$regexFind: { input: "$fname", regex: /(C(ar)*)ol/ }
}
}
}
])

The regex pattern finds a match with fname values Carol and Colleen:

{ "_id" : 1, "returnObject" : { "match" : "Carol", "idx" : 0, "captures" : [ "Car", "ar" ] } }
{ "_id" : 2, "returnObject" : null }
{ "_id" : 3, "returnObject" : null }
{ "_id" : 4, "returnObject" : { "match" : "Col", "idx" : 0, "captures" : [ "C", null ] } }
{ "_id" : 5, "returnObject" : null }

The pattern contains the capture group (C(ar)*) which contains the nested group (ar). The elements in the captures array correspond to the two capture groups. If a matching document is not captured by a group (e.g. Colleen and the group (ar)), $regexFind replaces the group with a null placeholder.

Conforme o exemplo anterior, a array captures contém um elemento para cada grupo de captura (utilizando null para não capturas). Considere o seguinte exemplo que procura números de telefone com códigos de área da cidade de Nova York ao aplicar um or lógico de grupos de captura no campo phone. Cada grupo representa um código de área da cidade de Nova York:

db.contacts.aggregate([
{
$project: {
nycContacts: {
$regexFind: { input: "$phone", regex: /^(718).*|^(212).*|^(917).*/ }
}
}
}
])

For documents which are matched by the regex pattern, the captures array includes the matching capture group and replaces any non-capturing groups with null:

{ "_id" : 1, "nycContacts" : { "match" : "718-555-0113", "idx" : 0, "captures" : [ "718", null, null ] } }
{ "_id" : 2, "nycContacts" : { "match" : "212-555-8832", "idx" : 0, "captures" : [ null, "212", null ] } }
{ "_id" : 3, "nycContacts" : null }
{ "_id" : 4, "nycContacts" : null }
{ "_id" : 5, "nycContacts" : { "match" : "917-555-4414", "idx" : 0, "captures" : [ null, null, "917" ] } }

To illustrate the behavior of the $regexFind operator as discussed in this example, create a sample collection products with the following documents:

db.products.insertMany([
{ _id: 1, description: "Single LINE description." },
{ _id: 2, description: "First lines\nsecond line" },
{ _id: 3, description: "Many spaces before line" },
{ _id: 4, description: "Multiple\nline descriptions" },
{ _id: 5, description: "anchors, links and hyperlinks" },
{ _id: 6, description: "métier work vocation" }
])

By default, $regexFind performs a case-sensitive match. For example, the following aggregation performs a case-sensitive $regexFind on the description field. The regex pattern /line/ does not specify any grouping:

db.products.aggregate([
{ $addFields: { returnObject: { $regexFind: { input: "$description", regex: /line/ } } } }
])

A operação retorna o seguinte:

{ "_id" : 1, "description" : "Single LINE description.", "returnObject" : null }
{ "_id" : 2, "description" : "First lines\nsecond line", "returnObject" : { "match" : "line", "idx" : 6, "captures" : [ ] } }
{ "_id" : 3, "description" : "Many spaces before line", "returnObject" : { "match" : "line", "idx" : 23, "captures" : [ ] } }
{ "_id" : 4, "description" : "Multiple\nline descriptions", "returnObject" : { "match" : "line", "idx" : 9, "captures" : [ ] } }
{ "_id" : 5, "description" : "anchors, links and hyperlinks", "returnObject" : null }
{ "_id" : 6, "description" : "métier work vocation", "returnObject" : null }

O seguinte padrão regex /lin(e|k)/ especifica um agrupamento (e|k) no padrão:

db.products.aggregate([
{ $addFields: { returnObject: { $regexFind: { input: "$description", regex: /lin(e|k)/ } } } }
])

A operação retorna o seguinte:

{ "_id" : 1, "description" : "Single LINE description.", "returnObject" : null }
{ "_id" : 2, "description" : "First lines\nsecond line", "returnObject" : { "match" : "line", "idx" : 6, "captures" : [ "e" ] } }
{ "_id" : 3, "description" : "Many spaces before line", "returnObject" : { "match" : "line", "idx" : 23, "captures" : [ "e" ] } }
{ "_id" : 4, "description" : "Multiple\nline descriptions", "returnObject" : { "match" : "line", "idx" : 9, "captures" : [ "e" ] } }
{ "_id" : 5, "description" : "anchors, links and hyperlinks", "returnObject" : { "match" : "link", "idx" : 9, "captures" : [ "k" ] } }
{ "_id" : 6, "description" : "métier work vocation", "returnObject" : null }

Na opção de retorno, o idx campo é o índice ponto de código e não o índice de bytes. Para ilustrar, considere o seguinte exemplo que utiliza o padrão regex /tier/:

db.products.aggregate([
{ $addFields: { returnObject: { $regexFind: { input: "$description", regex: /tier/ } } } }
])

A operação retorna o seguinte onde somente o último registro corresponde ao padrão e o idx retornado é 2 (em vez de 3 se estiver utilizando um índice de bytes)

{ "_id" : 1, "description" : "Single LINE description.", "returnObject" : null }
{ "_id" : 2, "description" : "First lines\nsecond line", "returnObject" : null }
{ "_id" : 3, "description" : "Many spaces before line", "returnObject" : null }
{ "_id" : 4, "description" : "Multiple\nline descriptions", "returnObject" : null }
{ "_id" : 5, "description" : "anchors, links and hyperlinks", "returnObject" : null }
{ "_id" : 6, "description" : "métier work vocation",
"returnObject" : { "match" : "tier", "idx" : 2, "captures" : [ ] } }

Observação

Não é permitido especificar opções no campo regex e options.

To perform case-insensitive pattern matching, include the i option as part of the regex field or in the options field:

// Specify i as part of the regex field
{ $regexFind: { input: "$description", regex: /line/i } }
// Specify i in the options field
{ $regexFind: { input: "$description", regex: /line/, options: "i" } }
{ $regexFind: { input: "$description", regex: "line", options: "i" } }

For example, the following aggregation performs a case-insensitive $regexFind on the description field. The regex pattern /line/ does not specify any grouping:

db.products.aggregate([
{ $addFields: { returnObject: { $regexFind: { input: "$description", regex: /line/i } } } }
])

A operação retorna os seguintes documentos:

{ "_id" : 1, "description" : "Single LINE description.", "returnObject" : { "match" : "LINE", "idx" : 7, "captures" : [ ] } }
{ "_id" : 2, "description" : "First lines\nsecond line", "returnObject" : { "match" : "line", "idx" : 6, "captures" : [ ] } }
{ "_id" : 3, "description" : "Many spaces before line", "returnObject" : { "match" : "line", "idx" : 23, "captures" : [ ] } }
{ "_id" : 4, "description" : "Multiple\nline descriptions", "returnObject" : { "match" : "line", "idx" : 9, "captures" : [ ] } }
{ "_id" : 5, "description" : "anchors, links and hyperlinks", "returnObject" : null }
{ "_id" : 6, "description" : "métier work vocation", "returnObject" : null }

Observação

Não é permitido especificar opções no campo regex e options.

Para corresponder às âncoras especificadas (por exemplo, ^, $) para cada linha de uma string de múltiplas linhas, inclua a opção m como parte do campo regex ou no campo opções:

// Specify m as part of the regex field
{ $regexFind: { input: "$description", regex: /line/m } }
// Specify m in the options field
{ $regexFind: { input: "$description", regex: /line/, options: "m" } }
{ $regexFind: { input: "$description", regex: "line", options: "m" } }

O exemplo a seguir inclui as opções i e m para combinar linhas começando com a letra s ou S para strings de várias linhas:

db.products.aggregate([
{ $addFields: { returnObject: { $regexFind: { input: "$description", regex: /^s/im } } } }
])

A operação retorna o seguinte:

{ "_id" : 1, "description" : "Single LINE description.", "returnObject" : { "match" : "S", "idx" : 0, "captures" : [ ] } }
{ "_id" : 2, "description" : "First lines\nsecond line", "returnObject" : { "match" : "s", "idx" : 12, "captures" : [ ] } }
{ "_id" : 3, "description" : "Many spaces before line", "returnObject" : null }
{ "_id" : 4, "description" : "Multiple\nline descriptions", "returnObject" : null }
{ "_id" : 5, "description" : "anchors, links and hyperlinks", "returnObject" : null }
{ "_id" : 6, "description" : "métier work vocation", "returnObject" : null }

Observação

Não é permitido especificar opções no campo regex e options.

To ignore all unescaped white space characters and comments (denoted by the un-escaped hash # character and the next new-line character) in the pattern, include the s option in the options field:

// Specify x in the options field
{ $regexFind: { input: "$description", regex: /line/, options: "x" } }
{ $regexFind: { input: "$description", regex: "line", options: "x" } }

O exemplo a seguir inclui a opção x para ignorar espaços em branco e comentários sem escape:

db.products.aggregate([
{ $addFields: { returnObject: { $regexFind: { input: "$description", regex: /lin(e|k) # matches line or link/, options:"x" } } } }
])

A operação retorna o seguinte:

{ "_id" : 1, "description" : "Single LINE description.", "returnObject" : null }
{ "_id" : 2, "description" : "First lines\nsecond line", "returnObject" : { "match" : "line", "idx" : 6, "captures" : [ "e" ] } }
{ "_id" : 3, "description" : "Many spaces before line", "returnObject" : { "match" : "line", "idx" : 23, "captures" : [ "e" ] } }
{ "_id" : 4, "description" : "Multiple\nline descriptions", "returnObject" : { "match" : "line", "idx" : 9, "captures" : [ "e" ] } }
{ "_id" : 5, "description" : "anchors, links and hyperlinks", "returnObject" : { "match" : "link", "idx" : 9, "captures" : [ "k" ] } }
{ "_id" : 6, "description" : "métier work vocation", "returnObject" : null }

Observação

Não é permitido especificar opções no campo regex e options.

To allow the dot character (i.e. .) in the pattern to match all characters including the new line character, include the s option in the options field:

// Specify s in the options field
{ $regexFind: { input: "$description", regex: /m.*line/, options: "s" } }
{ $regexFind: { input: "$description", regex: "m.*line", options: "s" } }

O exemplo a seguir inclui a opção s para permitir que o caractere do ponto (ou seja, .) corresponda a todos os caracteres, incluindo uma nova linha, bem como a opção i para realizar uma correspondência entre maiúsculas e minúsculas:

db.products.aggregate([
{ $addFields: { returnObject: { $regexFind: { input: "$description", regex:/m.*line/, options: "si" } } } }
])

A operação retorna o seguinte:

{ "_id" : 1, "description" : "Single LINE description.", "returnObject" : null }
{ "_id" : 2, "description" : "First lines\nsecond line", "returnObject" : null }
{ "_id" : 3, "description" : "Many spaces before line", "returnObject" : { "match" : "Many spaces before line", "idx" : 0, "captures" : [ ] } }
{ "_id" : 4, "description" : "Multiple\nline descriptions", "returnObject" : { "match" : "Multiple\nline", "idx" : 0, "captures" : [ ] } }
{ "_id" : 5, "description" : "anchors, links and hyperlinks", "returnObject" : null }
{ "_id" : 6, "description" : "métier work vocation", "returnObject" : null }

Criar uma collection de amostra feedback com os seguintes documentos:

db.feedback.insertMany([
{ "_id" : 1, comment: "Hi, I'm just reading about MongoDB -- aunt.arc.tica@example.com" },
{ "_id" : 2, comment: "I wanted to concatenate a string" },
{ "_id" : 3, comment: "How do I convert a date to string? cam@mongodb.com" },
{ "_id" : 4, comment: "It's just me. I'm testing. fred@MongoDB.com" }
])

The following aggregation uses the $regexFind to extract the email from the comment field (case insensitive).

db.feedback.aggregate( [
{ $addFields: {
"email": { $regexFind: { input: "$comment", regex: /[a-z0-9_.+-]+@[a-z0-9_.+-]+\.[a-z0-9_.+-]+/i } }
} },
{ $set: { email: "$email.match"} }
] )
Primeira etapa

The stage uses the $addFields stage to add a new field email to the document. The new field contains the result of performing the $regexFind on the comment field:

{ "_id" : 1, "comment" : "Hi, I'm just reading about MongoDB -- aunt.arc.tica@example.com", "email" : { "match" : "aunt.arc.tica@example.com", "idx" : 38, "captures" : [ ] } }
{ "_id" : 2, "comment" : "I wanted to concatenate a string", "email" : null }
{ "_id" : 3, "comment" : "I can't find how to convert a date to string. cam@mongodb.com", "email" : { "match" : "cam@mongodb.com", "idx" : 46, "captures" : [ ] } }
{ "_id" : 4, "comment" : "It's just me. I'm testing. fred@MongoDB.com", "email" : { "match" : "fred@MongoDB.com", "idx" : 28, "captures" : [ ] } }
Segunda etapa

O estágio utiliza o estágio $set para redefinir o email ao valor "$email.match" atual. Se o valor atual de email for nulo, o novo valor de email será definido como nulo.

{ "_id" : 1, "comment" : "Hi, I'm just reading about MongoDB -- aunt.arc.tica@example.com", "email" : "aunt.arc.tica@example.com" }
{ "_id" : 2, "comment" : "I wanted to concatenate a string" }
{ "_id" : 3, "comment" : "I can't find how to convert a date to string. cam@mongodb.com", "email" : "cam@mongodb.com" }
{ "_id" : 4, "comment" : "It's just me. I'm testing. fred@MongoDB.com", "email" : "fred@MongoDB.com" }

Criar uma collection de amostra contacts com os seguintes documentos:

db.contacts.insertMany([
{ "_id" : 1, name: "Aunt Arc Tikka", details: [ "+672-19-9999", "aunt.arc.tica@example.com" ] },
{ "_id" : 2, name: "Belle Gium", details: [ "+32-2-111-11-11", "belle.gium@example.com" ] },
{ "_id" : 3, name: "Cam Bo Dia", details: [ "+855-012-000-0000", "cam.bo.dia@example.com" ] },
{ "_id" : 4, name: "Fred", details: [ "+1-111-222-3333" ] }
])

The following aggregation uses the $regexFind to convert the details array into an embedded document with an email and phone fields:

db.contacts.aggregate( [
{ $unwind: "$details" },
{ $addFields: {
"regexemail": { $regexFind: { input: "$details", regex: /^[a-z0-9_.+-]+@[a-z0-9_.+-]+\.[a-z0-9_.+-]+$/, options: "i" } },
"regexphone": { $regexFind: { input: "$details", regex: /^[+]{0,1}[0-9]*\-?[0-9_\-]+$/ } }
} },
{ $project: { _id: 1, name: 1, details: { email: "$regexemail.match", phone: "$regexphone.match" } } },
{ $group: { _id: "$_id", name: { $first: "$name" }, details: { $mergeObjects: "$details"} } },
{ $sort: { _id: 1 } }
])
Primeira etapa

O estágio $unwinds a array em documentos separados:

{ "_id" : 1, "name" : "Aunt Arc Tikka", "details" : "+672-19-9999" }
{ "_id" : 1, "name" : "Aunt Arc Tikka", "details" : "aunt.arc.tica@example.com" }
{ "_id" : 2, "name" : "Belle Gium", "details" : "+32-2-111-11-11" }
{ "_id" : 2, "name" : "Belle Gium", "details" : "belle.gium@example.com" }
{ "_id" : 3, "name" : "Cam Bo Dia", "details" : "+855-012-000-0000" }
{ "_id" : 3, "name" : "Cam Bo Dia", "details" : "cam.bo.dia@example.com" }
{ "_id" : 4, "name" : "Fred", "details" : "+1-111-222-3333" }
Segunda etapa

The stage uses the $addFields stage to add new fields to the document that contains the result of the $regexFind for phone number and email:

{ "_id" : 1, "name" : "Aunt Arc Tikka", "details" : "+672-19-9999", "regexemail" : null, "regexphone" : { "match" : "+672-19-9999", "idx" : 0, "captures" : [ ] } }
{ "_id" : 1, "name" : "Aunt Arc Tikka", "details" : "aunt.arc.tica@example.com", "regexemail" : { "match" : "aunt.arc.tica@example.com", "idx" : 0, "captures" : [ ] }, "regexphone" : null }
{ "_id" : 2, "name" : "Belle Gium", "details" : "+32-2-111-11-11", "regexemail" : null, "regexphone" : { "match" : "+32-2-111-11-11", "idx" : 0, "captures" : [ ] } }
{ "_id" : 2, "name" : "Belle Gium", "details" : "belle.gium@example.com", "regexemail" : { "match" : "belle.gium@example.com", "idx" : 0, "captures" : [ ] }, "regexphone" : null }
{ "_id" : 3, "name" : "Cam Bo Dia", "details" : "+855-012-000-0000", "regexemail" : null, "regexphone" : { "match" : "+855-012-000-0000", "idx" : 0, "captures" : [ ] } }
{ "_id" : 3, "name" : "Cam Bo Dia", "details" : "cam.bo.dia@example.com", "regexemail" : { "match" : "cam.bo.dia@example.com", "idx" : 0, "captures" : [ ] }, "regexphone" : null }
{ "_id" : 4, "name" : "Fred", "details" : "+1-111-222-3333", "regexemail" : null, "regexphone" : { "match" : "+1-111-222-3333", "idx" : 0, "captures" : [ ] } }
Terceiro estágio

O estágio usa o estágio $project para gerar documentos com os campos _id, name e details. O campo details é definido como um documento com os campos email e phone, cujos valores são determinados a partir dos campos regexemail e regexphone, respectivamente.

{ "_id" : 1, "name" : "Aunt Arc Tikka", "details" : { "phone" : "+672-19-9999" } }
{ "_id" : 1, "name" : "Aunt Arc Tikka", "details" : { "email" : "aunt.arc.tica@example.com" } }
{ "_id" : 2, "name" : "Belle Gium", "details" : { "phone" : "+32-2-111-11-11" } }
{ "_id" : 2, "name" : "Belle Gium", "details" : { "email" : "belle.gium@example.com" } }
{ "_id" : 3, "name" : "Cam Bo Dia", "details" : { "phone" : "+855-012-000-0000" } }
{ "_id" : 3, "name" : "Cam Bo Dia", "details" : { "email" : "cam.bo.dia@example.com" } }
{ "_id" : 4, "name" : "Fred", "details" : { "phone" : "+1-111-222-3333" } }
Quarto estágio

O estágio usa o estágio $group para agrupar os documentos de entrada por seu valor _id. O estágio usa a expressão $mergeObjects para mesclar os documentos details.

{ "_id" : 3, "name" : "Cam Bo Dia", "details" : { "phone" : "+855-012-000-0000", "email" : "cam.bo.dia@example.com" } }
{ "_id" : 4, "name" : "Fred", "details" : { "phone" : "+1-111-222-3333" } }
{ "_id" : 1, "name" : "Aunt Arc Tikka", "details" : { "phone" : "+672-19-9999", "email" : "aunt.arc.tica@example.com" } }
{ "_id" : 2, "name" : "Belle Gium", "details" : { "phone" : "+32-2-111-11-11", "email" : "belle.gium@example.com" } }
Quinto estágio

O estágio utiliza o estágio $sort para classificar os documentos pelo campo _id.

{ "_id" : 1, "name" : "Aunt Arc Tikka", "details" : { "phone" : "+672-19-9999", "email" : "aunt.arc.tica@example.com" } }
{ "_id" : 2, "name" : "Belle Gium", "details" : { "phone" : "+32-2-111-11-11", "email" : "belle.gium@example.com" } }
{ "_id" : 3, "name" : "Cam Bo Dia", "details" : { "phone" : "+855-012-000-0000", "email" : "cam.bo.dia@example.com" } }
{ "_id" : 4, "name" : "Fred", "details" : { "phone" : "+1-111-222-3333" } }

Criar uma collection de amostra employees com os seguintes documentos:

db.employees.insertMany([
{ "_id" : 1, name: "Aunt Arc Tikka", "email" : "aunt.tica@example.com" },
{ "_id" : 2, name: "Belle Gium", "email" : "belle.gium@example.com" },
{ "_id" : 3, name: "Cam Bo Dia", "email" : "cam.dia@example.com" },
{ "_id" : 4, name: "Fred" }
])

The employee email has the format <firstname>.<lastname>@example.com. Using the captured field returned in the $regexFind results, you can parse out user names for employees.

db.employees.aggregate( [
{ $addFields: {
"username": { $regexFind: { input: "$email", regex: /^([a-z0-9_.+-]+)@[a-z0-9_.+-]+\.[a-z0-9_.+-]+$/, options: "i" } },
} },
{ $set: { username: { $arrayElemAt: [ "$username.captures", 0 ] } } }
] )
Primeira etapa

The stage uses the $addFields stage to add a new field username to the document. The new field contains the result of performing the $regexFind on the email field:

{ "_id" : 1, "name" : "Aunt Arc Tikka", "email" : "aunt.tica@example.com", "username" : { "match" : "aunt.tica@example.com", "idx" : 0, "captures" : [ "aunt.tica" ] } }
{ "_id" : 2, "name" : "Belle Gium", "email" : "belle.gium@example.com", "username" : { "match" : "belle.gium@example.com", "idx" : 0, "captures" : [ "belle.gium" ] } }
{ "_id" : 3, "name" : "Cam Bo Dia", "email" : "cam.dia@example.com", "username" : { "match" : "cam.dia@example.com", "idx" : 0, "captures" : [ "cam.dia" ] } }
{ "_id" : 4, "name" : "Fred", "username" : null }
Segunda etapa

O estágio usa o estágio $set para redefinir o username para o elemento "zerésimo" da array "$username.captures". Se o valor atual de username for nulo, o novo valor de username será definido como nulo.

{ "_id" : 1, "name" : "Aunt Arc Tikka", "email" : "aunt.tica@example.com", "username" : "aunt.tica" }
{ "_id" : 2, "name" : "Belle Gium", "email" : "belle.gium@example.com", "username" : "belle.gium" }
{ "_id" : 3, "name" : "Cam Bo Dia", "email" : "cam.dia@example.com", "username" : "cam.dia" }
{ "_id" : 4, "name" : "Fred", "username" : null }

Dica

For more information on the behavior of the captures array and additional examples, see captures Output Behavior.