Skip to content

$literal

The $literal operator returns a constant value without interpreting it as a field path or expression.


📌 Syntax

{ "$literal": <value> }
  • <value> can be a string, number, object, array, or other raw constant.

✅ Base Example – Return a Constant String

📥 Input Document

{ "name": "Alice" }

📌 Expression

{ "$literal": "Hello World" }

📤 Output

"Hello World"

✅ Base Example – Return Constant Object

📥 Input Document

{}

📌 Expression

{
  "$literal": { "x": 1, "y": 2 }
}

📤 Output

{ "x": 1, "y": 2 }

🧱 Ecommerce Example – Inject Static Tax Field

📌 Pipeline

[
  {
    "$project": {
      "product": "$name",
      "taxRate": { "$literal": 0.15 }
    }
  }
]

📥 Input Document

{ "name": "Smartphone", "price": 999 }

📤 Output

{ "product": "Smartphone", "taxRate": 0.15 }

🔧 Common Use Cases

  • Force a static value in dynamic documents
  • Prevent evaluation of field paths or expressions
  • Embed objects or arrays literally

  • $const (MongoDB alternative), $toString, $type, $mergeObjects

🧠 Notes

  • Useful inside $project, $group, $addFields
  • Does not evaluate inner values — used exactly as written