Introduction to MongoDB $literal Operator

$literal is an aggregation pipeline operator in MongoDB that can be used to return a literal value from a document. Typically, the $literal operator is used when manually specifying a literal value as input to an aggregation pipeline. The $literal operator does not evaluate its expression but returns it as a literal value in the document.

Syntax

The syntax for the $literal operator is as follows:

{ $literal: <expression> }

Here, <expression> is the literal value to be returned.

Use Cases

A typical use case for using $literal is to specify a literal value in the input of an aggregation pipeline. If a document or value needs to be specified in an aggregation pipeline, but cannot be generated by other pipeline operators or expressions, then $literal can be used to specify that document or value. Additionally, $literal can also be used to force the output of other pipeline operators to be converted to a literal value.

Example

Assume we have the following collection of documents called students:

{
  "name": "Alice",
  "age": 18,
  "scores": [90, 85, 95]
},
{
  "name": "Bob",
  "age": 20,
  "scores": [80, 75, 70]
}

Now, let’s say we need to extend the scores field in all documents to a new field total_score whose value is the sum of all elements in the scores array. Since this operation cannot be directly performed by an aggregation pipeline, we need to use the $project operator and the $literal operator to manually specify the literal value. The following is the aggregation pipeline:

db.students.aggregate([
  {
    $project: {
      name: 1,
      age: 1,
      total_score: {
        $sum: "$scores"
      },
      scores: 1,
      _id: 0,
      literal_field: { $literal: "This is a literal field" }
    }
  }
])

In the above aggregation pipeline, we use the $literal operator to specify a new field literal_field whose value is the literal value "This is a literal field".

Conclusion

The $literal operator is a simple but very useful operator that can be used to specify literal values in aggregation pipelines. In some cases, using $literal can help us create complex aggregation pipelines more easily.