$literal (aggregation)

Definition

  • $literal
  • Returns a value without parsing. Use for values that the aggregationpipeline may interpret as an expression.

The $literal expression has the following syntax:

  1. { $literal: <value> }

Behavior

If the <value> is an expression,$literal does not evaluate the expression but insteadreturns the unparsed expression.

Example Result
{ $literal: { $add: [ 2, 3 ] } } { "$add" : [ 2, 3 ] }
{ $literal: { $literal: 1 } } { "$literal" : 1 }

Examples

Treat $ as a Literal

In expression,the dollar sign $ evaluates to a field path; i.e. provides accessto the field. For example, the $eq expression $eq: ["$price", "$1" ] performs an equality check between the value in thefield named price and the value in the field named 1 in thedocument.

The following example uses a $literal expression to treata string that contains a dollar sign "$1" as a constant value.

A collection records has the following documents:

  1. { "_id" : 1, "item" : "abc123", price: "$2.50" }
  2. { "_id" : 2, "item" : "xyz123", price: "1" }
  3. { "_id" : 3, "item" : "ijk123", price: "$1" }
  1. db.records.aggregate( [
  2. { $project: { costsOneDollar: { $eq: [ "$price", { $literal: "$1" } ] } } }
  3. ] )

This operation projects a field named costsOneDollar that holds aboolean value, indicating whether the value of the price field isequal to the string "$1":

  1. { "_id" : 1, "costsOneDollar" : false }
  2. { "_id" : 2, "costsOneDollar" : false }
  3. { "_id" : 3, "costsOneDollar" : true }

Project a New Field with Value 1

The $project stage uses the expression <field>: 1 toinclude the <field> in the output. The following example uses the$literal to return a new field set to the value of 1.

A collection bids has the following documents:

  1. { "_id" : 1, "item" : "abc123", condition: "new" }
  2. { "_id" : 2, "item" : "xyz123", condition: "new" }

The following aggregation evaluates the expression item: 1 to meanreturn the existing field item in the output, but uses the{ $literal: 1 } expression to return a newfield startAt set to the value 1:

  1. db.bids.aggregate( [
  2. { $project: { item: 1, startAt: { $literal: 1 } } }
  3. ] )

The operation results in the following documents:

  1. { "_id" : 1, "item" : "abc123", "startAt" : 1 }
  2. { "_id" : 2, "item" : "xyz123", "startAt" : 1 }