MongoDB $literal

In MongoDB, the $literal aggregation pipeline operator returns a value without parsing.

It accepts any valid expression, and returns the unparsed expression.

The $literal operator can be useful for when you have a value that MongoDB could inadvertently interpret as an expression, but you don’t want it to.

For example, if you have a monetary amount that includes a dollar sign, MongoDB might inadvertently interpret that as a field name. You can use $literal to prevent MongoDB from interpreting such expressions.

Example

Suppose we have a collection called test with the following document:

{ "_id" : 1, "name" : "Homer" }

Here’s an example of applying $literal:

db.test.aggregate(
  [
    { $match: { _id: { $in: [ 1 ] } } },
    {
      $project:
        { 
          _id: 0,
          interpreted: "$name",
          literal: { $literal: "$name" }
        }
    }
  ]
)

Result:

{ "interpreted" : "Homer", "literal" : "$name" }

In this example, we return the value of the name field by using $name to refer to it.

We also return the literal value $name, without having MongoDB interpret it to mean the name field:

Example 2

Suppose our collection contains the following document:

{ "_id" : 2, "a" : 10, "b" : 5 }

Here’s another example of using $literal:

db.test.aggregate(
  [
    { $match: { _id: { $in: [ 2 ] } } },
    {
      $project:
        { 
          _id: 0,
          interpreted: { $multiply: [ "$a", "$b" ] },
          literal: { $literal: { $multiply: [ "$a", "$b" ] } }
        }
    }
  ]
)

Result:

{ "interpreted" : 50, "literal" : { "$multiply" : [ "$a", "$b" ] } }

In this case, the first field returned contains the result of the $multiply operator against the a and b fields.

The second field simply outputs the literal value that we provided to the $literal operator.