MongoDB $toString Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $toString?

$toString is a MongoDB aggregation expression that converts a value to its string form. Numbers become text like "42", ObjectIds become 24-character hex strings, and booleans become "true" / "false". Use it when you need text for $concat, exports, or display labels.

Remember
$toString = String() for aggregation

{ $toString: <expression> }

number   → "42"
boolean  → "true" / "false"
ObjectId → 24-char hex
null / missing → null

Pair with $concat for labels
Dates: prefer $dateToString for formats
UsePrefer
Any value → string$toString
Build a text label$concat + $toString
Custom date format$dateToString

How to Use $toString in MongoDB

Pick the field to stringify, convert it, then use the result in labels or exports.

  1. Choose an expression stage ($addFields or $project).
  2. Pass the field or expression to $toString.
  3. If building text, wrap every non-string piece before $concat.
  4. Keep the original typed field when you still need math or sorting.
PieceRequired?Role
$toStringYesConvert value → string
ExpressionYesField, literal, or nested expression
$concatNoJoin strings into a display label

Pseudocode

Pseudocode
for each document:
    v = evaluate(expression)
    if v is null or missing:
        result = null
    else:
        result = String(v)   // type-specific text form
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing type-conversion expressions.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $toString: <expression> }
Equivalent{ $convert: { input: <expr>, to: "string" } }
Number150 → "150"
ObjectId→ 24-character hex string
Label pattern$concat: ["Score: ", { $toString: "$score" }]
Nullnull / missing → null

Live Preview

Watch $toString turn a value into text. Pick a sample input and run the conversion.

Simulates $toString the same way as the mongosh examples below.

Result
input = 150 (number)
$type → "int" / "double" (numeric)

$toString(input) → "150"

{ stockText: "150" }

Worked Walkthrough — Product Label

One product: name Widget, price 29.99, stock 150. Goal: one readable label string for a report.

Calculation
Document:
  { name: "Widget", price: 29.99, stock: 150 }

$toString("$price") → "29.99"
$toString("$stock") → "150"

$concat: [
  "$name", " — $", priceText, " (", stockText, " in stock)"
]

Result:
  "Widget — $29.99 (150 in stock)"

MongoDB Examples

We use a small products collection. First convert a number to text, then build a display label with $concat. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine two products. We save name, price, and stock as documents in a collection named products.

mongosh
db.products.insertMany([
  { _id: 1, name: "Widget", price: 29.99, stock: 150 },
  { _id: 2, name: "Gadget", price: 49.50, stock: 75 }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps two documents in products. Run find() to see them:

mongosh
db.products.find()

Read each document like this:

Field in MongoDBExamplePlain English
_id1Document id (row number for this lesson)
name"Widget"Product name (already a string)
price29.99Price as a number
stock150Units in stock as a number

How It Works

  1. Insert once. insertMany adds two product documents to products.
  2. MongoDB stores types as written. price and stock stay numbers; name stays a string.
  3. find() shows the same shape. What you inserted is what you get back—ready for $toString next.

Example 2 — Number to String

Goal: add a stockText field that is the string form of stock, without changing the original number.

mongosh
db.products.aggregate([
  {
    $addFields: {
      stockText: { $toString: "$stock" }
    }
  }
]);

How It Works

  1. Read the stored number. Widget has stock: 150 from Example 1.
  2. Convert to text. $toString: "$stock" → "150".
  3. Keep all fields. $addFields adds stockText; the numeric stock stays for math or sorting.

Example 3 — Label with $concat

Same products, but build one display string. Wrap every number in $toString first—$concat only accepts strings.

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      label: {
        $concat: [
          "$name",
          " — $",
          { $toString: "$price" },
          " (",
          { $toString: "$stock" },
          " in stock)"
        ]
      }
    }
  }
]);

How It Works

  1. Same stored documents. Still using Widget and Gadget from Example 1.
  2. Stringify numbers. $toString turns price and stock into text.
  3. Join the pieces. $concat stitches name, currency text, and counts into one label.
  4. Easy check. Widget’s label should read Widget — $29.99 (150 in stock).

Edge Cases & Pitfalls

Check these before using $toString in production pipelines.

concat

$concat needs strings

Passing a number or ObjectId directly to $concat fails. Wrap non-strings with $toString first.

dates

Prefer $dateToString for formats

$toString on a date gives ISO-8601. Use $dateToString when you need a custom pattern.

null

Null and missing become null

Missing fields return null, not an empty string. Guard with $ifNull if you need a default.

types

Keep typed fields for math

Do not overwrite numbers with strings if you still need $sum, $sort, or comparisons. Add a separate text field instead.

Performance Notes

ApproachCostBest for
$toString alonePer-document convertExport / display fields
$toString + $concatStill O(docs)Labels and SKU-style strings
Stringify lateFewer conversionsPipelines that filter first

Type conversion is cheap compared with large sorts or joins. Filter early with $match when only some documents need a label.

Key Takeaways

  • Role: any value → string in aggregation.
  • Labels: wrap numbers/ObjectIds before $concat.
  • Dates: prefer $dateToString for custom formats.
  • Null: null / missing → null.

One line: $toString answers “what is this value as text?”—so you can concat, export, or display it safely.

Frequently Asked Questions

$toString converts a value to its string representation inside an aggregation pipeline. Numbers become decimal text, ObjectIds become 24-character hex strings, and booleans become "true" or "false".
Use { $toString: <expression> }. The expression can be a field path like "$price", a literal, or any nested expression you want to stringify.
Use it before $concat when mixing numbers or ObjectIds with text, when exporting IDs as hex strings, or when building display labels and SKU codes from mixed field types.
$toString gives a default string form for any type (dates become ISO-8601). Prefer $dateToString when you need a custom date format such as YYYY-MM-DD.
$toString returns null when the input is null or the field is missing. It does not throw an error for null input.
Yes for the idea. Think of $toString as MongoDB’s aggregation version of String()—run it in the pipeline, not as a standalone find() filter.

Next: $toUpper

Convert a string to uppercase inside an aggregation pipeline.

$toUpper tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

9 people found this page helpful