Definição
$literalRetorna um valor sem analisar. Use para valores que o aggregation pipeline pode interpretar como uma expressão.
The
$literalexpression has the following syntax:{ $literal: <value> }
Comportamento
If the <value> is an expression, $literal does not evaluate the expression but instead returns the unparsed expression.
Exemplo | Resultado |
|---|---|
|
|
|
|
Exemplos
Trate $ como um Literal
Na expressão, o cifrão $ é avaliado como um caminho de campo; ou seja, fornece acesso ao campo. Por exemplo, a expressão $eq $eq: [ "$price", "$1" ] executa uma verificação de igualdade entre o valor no campo denominado price e o valor no campo denominado 1 no documento.
The following example uses a $literal expression to treat a string that contains a dollar sign "$1" as a constant value.
Uma coleção storeInventory tem os seguintes documentos:
db.storeInventory.insertMany( [ { "_id" : 1, "item" : "napkins", price: "$2.50" }, { "_id" : 2, "item" : "coffee", price: "1" }, { "_id" : 3, "item" : "soap", price: "$1" } ] )
db.storeInventory.aggregate( [ { $project: { costsOneDollar: { $eq: [ "$price", { $literal: "$1" } ] } } } ] )
Esta operação projeta um campo denominado costsOneDollar que detém um valor booleano, indicando se o valor do campo price é igual à string "$1":
{ "_id" : 1, "costsOneDollar" : false } { "_id" : 2, "costsOneDollar" : false } { "_id" : 3, "costsOneDollar" : true }
Projetar um novo campo com valor 1
The $project stage uses the expression <field>: 1 to include the <field> in the output. The following example uses the $literal to return a new field set to the value of 1.
Uma coleção books tem os seguintes documentos:
db.books.insertMany([ { "_id" : 1, "title" : "Dracula", "condition": "new" }, { "_id" : 2, "title" : "The Little Prince", "condition": "new" } ])
The { $literal: 1 } expression returns a new editionNumber field set to the value 1:
db.books.aggregate( [ { $project: { "title": 1, "editionNumber": { $literal: 1 } } } ] )
A operação resulta nos seguintes documentos:
{ "_id" : 1, "title" : "Dracula", "editionNumber" : 1 } { "_id" : 2, "title" : "The Little Prince", "editionNumber" : 1 }