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

$getField (operador de expressão )

$getField

Novidade na versão 5.0.

Returns the value of a specified field from a document. If you don't specify an object, $getField returns the value of the field from $$CURRENT.

You can use $getField to retrieve the value of fields with names that contain periods (.) or start with dollar signs ($).

Não confie em nomes de campo com prefixo de dólar de nível raiz que colidem com nomes de campo de metadados internos reservados, pois esses campos podem ser descartados ou inacessíveis em alguns contextos de processamento de query. Para restrições e orientações sobre nomes de campo que contêm cifrões ($) ou pontos (.), consulte Nomes de campo com pontos e cifrões.

Dica

Use $setField para adicionar ou atualizar campos com nomes que contenham cifrões ($) ou pontos (.).

$getField tem a seguinte sintaxe:

{
$getField: {
field: <String>,
input: <Object>
}
}
Campo
Tipo
Descrição

field

String

Campo no objeto input para o qual você deseja retornar um valor. O field pode ser qualquer expressão válida que resolva para uma constante de string.

Se o field começar com um sinal de dólar ($), coloque o nome do campo dentro de uma expressão $literal para retornar seu valor.

input

Objeto

Padrão: $$CURRENT

Uma expressão válida que contém o field para o qual você deseja retornar um valor. input deve resolver para um objeto, missing, null ou undefined. Se omitido, o padrão é o documento atualmente sendo processado no pipeline ($$CURRENT).

$getField has the following shorthand syntax for retrieving field values from $$CURRENT:

{
$getField: <String>
}

Para esta sintaxe, o argumento é equivalente ao valor de field descrito acima.

  • If field resolves to anything other than a string constant, $getField returns an error.

  • If the field that you specify is not present in the input object, or in $$CURRENT if you don't specify an input object, $getField returns missing.

  • If input evaluates to missing, undefined, or null, $getField returns null.

  • If input evaluates to anything other than an object, missing, undefined, or null, $getField returns an error.

  • $getField doesn't implicitly traverse objects or arrays. For example, $getField evaluates a field value of a.b.c as a top-level field a.b.c instead of a nested field { a: { b: { c: } } }.

Considere uma coleção inventory com os seguintes documentos:

db.inventory.insertMany( [
{ _id: 1, item: "sweatshirt", "price.usd": 45.99, qty: 300 },
{ _id: 2, item: "winter coat", "price.usd": 499.99, qty: 200 },
{ _id: 3, item: "sun dress", "price.usd": 199.99, qty: 250 },
{ _id: 4, item: "leather boots", "price.usd": 249.99, qty: 300 },
{ _id: 5, item: "bow tie", "price.usd": 9.99, qty: 180 }
] )

The following operation uses the $getField and $gt operators to find which products have a price.usd greater than 200:

db.inventory.aggregate( [
{
$match:
{ $expr:
{ $gt: [ { $getField: "price.usd" }, 200 ] }
}
}
] )

A operação retorna os seguintes resultados:

[
{ _id: 2, item: 'winter coat', qty: 200, 'price.usd': 499.99 },
{ _id: 4, item: 'leather boots', qty: 300, 'price.usd': 249.99 }
]

Considere uma coleção inventory com os seguintes documentos:

db.inventory.insertMany( [
{ _id: 1, item: "sweatshirt", "$price": 45.99, qty: 300 },
{ _id: 2, item: "winter coat", "$price": 499.99, qty: 200 },
{ _id: 3, item: "sun dress", "$price": 199.99, qty: 250 },
{ _id: 4, item: "leather boots", "$price": 249.99, qty: 300 },
{ _id: 5, item: "bow tie", "$price": 9.99, qty: 180 }
] )

The following operation uses the $getField, $gt, and $literal operators to find which products have a $price greater than 200:

db.inventory.aggregate( [
{
$match:
{ $expr:
{ $gt: [ { $getField: {$literal: "$price" } }, 200 ] }
}
}
] )

A operação retorna os seguintes resultados:

[
{ _id: 2, item: 'winter coat', qty: 200, '$price': 499.99 },
{ _id: 4, item: 'leather boots', qty: 300, '$price': 249.99 }
]

Cria uma collection inventory com os seguintes documentos:

db.inventory.insertMany( [
{ _id: 1, item: "sweatshirt", "price.usd": 45.99,
quantity: { "$large": 50, "$medium": 50, "$small": 25 }
},
{ _id: 2, item: "winter coat", "price.usd": 499.99,
quantity: { "$large": 35, "$medium": 35, "$small": 35 }
},
{ _id: 3, item: "sun dress", "price.usd": 199.99,
quantity: { "$large": 45, "$medium": 40, "$small": 5 }
},
{ _id: 4, item: "leather boots", "price.usd": 249.99,
quantity: { "$large": 20, "$medium": 30, "$small": 40 }
},
{ _id: 5, item: "bow tie", "price.usd": 9.99,
quantity: { "$large": 0, "$medium": 10, "$small": 75 }
}
] )

A operação seguinte retorna documentos onde o número de $small itens é menor ou igual a 20.

db.inventory.aggregate( [
{ $match:
{ $expr:
{ $lte:
[
{ $getField:
{ field: { $literal: "$small" },
input: "$quantity"
}
},
20
]
}
}
}
] )

Use estes operadores para consultar a coleção:

  • O operador $lte localiza valores menores ou iguais a 20.

  • $getField requer parâmetros field e input explícitos porque o campo $small faz parte de um subdocumento.

  • $getField uses $literal to evaluate "$small", because the field name has a dollar sign ($) in it.

Saída de exemplo:

[
{
_id: 3,
item: 'sun dress',
'price.usd': 199.99,
quantity: { '$large': 45, '$medium': 40, '$small': 5 }
}
]