MongoDB $literal Operator

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 4 Examples
Constants

What You’ll Learn

The $literal operator returns a constant value in an aggregation expression. MongoDB does not treat it as a field path, which matters when your value starts with $ or when you need a fixed array or object inside another operator.

01

Constant Values

Fixed strings and numbers.

02

Syntax

{ $literal: value }.

03

Field vs Literal

When $ matters.

04

Arrays & Objects

Literal collections.

05

Use Cases

Labels, defaults, tags.

06

With Operators

$cond, $concatArrays.

Definition and Usage

In MongoDB’s aggregation framework, the $literal operator evaluates to the value you provide — exactly as written. Unlike a plain string in an expression, $literal prevents MongoDB from interpreting $-prefixed strings as field references.

For example, "$price" in $project normally reads the price field from the document. Wrapping it as { $literal: "$price" } outputs the string "$price" instead.

💡
Beginner Tip

Plain constants like "USD" or 42 often work without $literal in simple $project fields. Reach for $literal when the value could be parsed as a field path, or when an operator expects an expression object rather than a raw constant.

📝 Syntax

The $literal operator wraps a single constant value:

mongosh
{ $literal: <value> }

Common Patterns

mongosh
// String constant
{ $literal: "USD" }

// Number constant
{ $literal: 100 }

// Prevent field-path parsing
{ $literal: "$price" }

// Literal array
{ $literal: [ "draft", "published" ] }

// Literal object
{ $literal: { role: "admin", active: true } }

Syntax Rules

  • Single argument$literal takes one value: string, number, boolean, null, array, or object.
  • No field parsing — MongoDB returns the value as-is; strings starting with $ are not treated as paths.
  • Expression operator — use inside $project, $addFields, $set, and nested expressions.
  • Not a pipeline stage$literal is an expression, not a stage like $match.
  • Arrays and objects — wrap full arrays or objects when an operator requires an expression form.

💡 Field Reference vs $literal

"$price" → reads the price field from the document
{ $literal: "$price" } → outputs the string "$price"
"USD" → plain string constant (no field lookup)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (constants)
Syntax{ $literal: <value> }
OutputThe wrapped constant value
Main purposeAvoid field-path interpretation of $ strings
Common stages$project, $addFields, nested in $cond
String
{
  $literal: "USD"
}

Currency label

$ string
{
  $literal: "$price"
}

Not a field path

Array
{
  $literal: [
    "a", "b"
  ]
}

Fixed list

In $cond
{
  $cond: [
    { $gte: [
      "$score", 80
    ]},
    { $literal: "pass" },
    { $literal: "fail" }
  ]
}

Branch labels

Examples Gallery

Walk through a sample products collection and see when plain values work, when $literal is required, and how to combine literals with other operators.

📚 Constants in $project

Add fixed labels and defaults to documents without reading from fields.

Sample Input Documents

Suppose you have a products collection:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "name": "Notebook", "price": 12.50, "tags": [ "stationery" ] },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "name": "Pen Pack", "price": 8.99, "tags": [ "stationery", "writing" ] },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "name": "Stapler", "price": 15.00, "tags": [ "office" ] }
]

Example 1 — Add a Fixed Currency Label

Add currency: "USD" to every product using $literal:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      price: 1,
      currency: { $literal: "USD" }
    }
  }
])

How It Works

  • { $literal: "USD" } evaluates to the string "USD" for every document.
  • For simple strings without $, you can often write currency: "USD" directly in $project.
  • $literal is explicit and required inside nested expression operators.

📈 When $literal Is Required

Prevent field-path parsing and pass literal arrays into other operators.

Example 2 — Output a String That Starts With $

Compare a field reference with a literal $-prefixed string:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      fieldRef: "$price",
      literalString: { $literal: "$price" }
    }
  }
])

How It Works

Without $literal, "$price" is a field path. With $literal, MongoDB returns the exact string — useful for documentation fields, template placeholders, or debugging output.

Example 3 — $literal Inside $cond

Assign pass/fail labels based on a price threshold:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      price: 1,
      tier: {
        $cond: [
          { $gte: [ "$price", 12 ] },
          { $literal: "premium" },
          { $literal: "budget" }
        ]
      }
    }
  }
])

How It Works

Inside $cond, branch values must be expressions. $literal makes it clear you want fixed string constants, not field lookups.

Example 4 — Literal Array with $concatArrays

Append a fixed list of default tags to each product’s tags array:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      allTags: {
        $concatArrays: [
          "$tags",
          { $literal: [ "in-stock", "catalog" ] }
        ]
      }
    }
  }
])

How It Works

$concatArrays expects expression arguments. { $literal: [ "in-stock", "catalog" ] } supplies a constant array to merge with each document’s tags field.

Bonus — Literal Object for Metadata

Add a fixed metadata object to every document:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      price: 1,
      meta: {
        $literal: {
          source: "catalog-import",
          version: 1,
          active: true
        }
      }
    }
  }
])

How It Works

$literal can wrap objects and arrays. Every document receives the same meta structure without reading from fields.

🚀 Use Cases

  • Fixed labels — add currency codes, status strings, or category names to output.
  • $-prefixed strings — output template tokens like "$price" without field lookup.
  • Default values in expressions — supply constants inside $cond, $switch, or $ifNull branches.
  • Literal arrays/objects — pass fixed collections to $concatArrays, $setUnion, or $in.

🧠 How $literal Works

1

You wrap a value

Provide the constant inside { $literal: ... } in an aggregation expression.

Input
2

MongoDB skips field parsing

Unlike "$price", the wrapped value is not treated as a document field path.

Parse
3

The constant is returned

The expression evaluates to your value — string, number, array, or object — for each document.

Output
=

Predictable constants

Your pipeline outputs exactly the fixed value you intended, with no accidental field lookups.

Conclusion

The $literal operator is the safe way to include constant values in aggregation expressions. Use it when a value might be mistaken for a field path, or when another operator expects an expression object rather than a bare constant.

For simple $project fields, plain strings and numbers often suffice. Inside nested operators like $cond and $concatArrays, $literal makes your intent explicit and prevents subtle parsing mistakes.

💡 Best Practices

✅ Do

  • Use $literal for strings that start with $
  • Wrap arrays/objects when passing them into expression operators
  • Use $literal in $cond branches for fixed strings
  • Prefer explicit literals in complex nested expressions
  • Test output when mixing field paths and constants

❌ Don’t

  • Assume "$field" is a string — it is a field path
  • Use $literal as a pipeline stage
  • Wrap field references you actually want to read
  • Overuse $literal for simple top-level $project strings
  • Confuse $literal with $let variables ($$name)

Key Takeaways

Knowledge Unlocked

Five things to remember about $literal

Use these points when adding constants to aggregation expressions.

5
Core concepts
🔢 02

$ Strings

No field parsing.

Syntax
🛠 03

Any BSON Type

String to object.

Types
🔄 04

In $cond

Fixed branch labels.

Pattern
📑 05

With Arrays

$concatArrays etc.

Advanced

❓ Frequently Asked Questions

$literal returns a constant value in an aggregation expression without treating strings that start with $ as field paths. Use it when you need a fixed string, number, array, or object in $project, $addFields, or nested expressions.
The syntax is { $literal: <value> }. The value can be a string, number, boolean, null, array, or object. MongoDB returns it exactly as written, without field-path parsing.
Use $literal when a value would be misread as a field reference. For example, "$price" normally reads the price field, but { $literal: "$price" } outputs the string "$price". It is also useful for literal arrays inside operators like $concatArrays.
Yes. $literal supports strings, numbers, booleans, null, arrays, and objects. MongoDB returns the wrapped value as a constant in the expression result.
Use $literal inside expression stages such as $project, $addFields, $set, and within other operators like $cond, $concatArrays, $in, and $setEquals when you need fixed constant values.

Continue the Operator Series

Move on to $ln for natural logarithm calculations, or review $let for local variables.

Next: $ln →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful