$literal (Literal)
Last updated: 2026-10-09
$literal (Literal)
$literal returns a value without parsing it as an expression. It is used when a string starting with $ should stay plain text, or when a numeric literal must keep its exact type. For example { $project: { prefix: { $literal: '$' } } } outputs the string '$', while writing '$' directly would be treated as a field path. $literal is also handy for literal boolean or numeric arguments inside $cond or $switch. It is the most concise way to emit a constant in $project.
| Category | Literal, Variable & Object |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $literal: <value> }
⚙️ Parameters
| value | Any value or expression; strings starting with $ are treated literally. |
|---|
Returns:The value passed in, returned as-is without expression parsing
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $literal: emit string constants starting with $
db.orders.aggregate([
{ $project: {
currency: { $literal: '$' },
rate: { $literal: 0.08 }
} }
])
Output:
{ '_id': 1, 'currency': '$', 'rate': 0.08 }
{ '_id': 2, 'currency': '$', 'rate': 0.08 }
📌 Notes
- A string starting with $ written directly is parsed as a field path; use $literal
- Expressions inside $literal are not evaluated
- Often pairs with $cond or $ifNull to provide defaults
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is $literal for?
AEmit constants such as $ strings without them being parsed as field paths.
QWhat happens without $literal?
AA $ string would be parsed as a field path and resolve to null when the field is absent.
QCan $literal wrap an expression?
AIt would not evaluate it; the literal content is returned as-is.