MongoDB $toString Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
Type Conversion

What You’ll Learn

The $toString operator converts any value to a string in MongoDB aggregation pipelines. Use it to build text labels with $concat, display ObjectIds, format numbers for export, and combine mixed-type fields.

01

Stringify

Any value to text.

02

Syntax

One expression.

03

$concat

Build labels.

04

ObjectId

ID to hex text.

05

Use Cases

Export, display.

06

vs $toObjectId

String ↔ ID.

Definition and Usage

In MongoDB’s aggregation framework, the $toString operator converts an expression to its string representation. Numbers become text like "42", ObjectIds become 24-character hex strings, and booleans become "true" or "false". This is essential when you need to combine values of different types using $concat or display them in reports.

$toString is shorthand for { $convert: { input: <expression>, to: "string" } }. It is the reverse of operators like $toInt and $toObjectId, which parse strings into typed values.

💡
Beginner Tip

$concat only works with strings. Wrap numeric or ObjectId fields in $toString before concatenating them with text labels.

📝 Syntax

The $toString operator takes one expression:

mongosh
{ $toString: <expression> }

Literal Examples

mongosh
{ $toString: 42 }
// Result: "42"

{ $toString: true }
// Result: "true"

{ $toString: "$_id" }
// ObjectId → "507f1f77bcf86cd799439011"

{ $toString: "$score" }
// Number field → string

Conversion Rules

  • null — returns null.
  • String — returns the same string unchanged.
  • Number — converts to decimal string (e.g. 42"42").
  • Booleantrue"true", false"false".
  • ObjectId — converts to 24-character hex string.
  • Date — converts to ISO-8601 string (use $dateToString for custom date formats).
  • Use inside $project, $addFields, or $set.

💡 $toString vs $toObjectId vs $dateToString

$toString — any value → string (general purpose)
$toObjectId — 24-char hex string → ObjectId (reverse of $toString on IDs)
$dateToString — date → formatted string with custom pattern (preferred for dates)
Use $toString for general conversion; use specialized operators when you need specific formats

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (type conversion)
Syntax{ $toString: <expression> }
Output typeString
Equivalent{ $convert: { input: <expr>, to: "string" } }
Common pairing$concat for building text labels
Common stages$project, $addFields, $set
Number
{
  $toString: "$score"
}

42 → "42"

ObjectId
{
  $toString: "$_id"
}

ID to hex text

$concat
{
  $concat: [
    "Score: ",
    { $toString: "$score" }
  ]
}

Build label

Boolean
{
  $toString: "$active"
}

true → "true"

Examples Gallery

Convert numbers and ObjectIds to strings, build labels with $concat, and format values for export and display.

📚 Product Labels

Start with a products collection and convert numeric fields to strings for display labels.

Sample Input Documents

Suppose you have a products collection:

mongosh
[
  {
    "_id": ObjectId("507f1f77bcf86cd799439011"),
    "name": "Widget",
    "price": 29.99,
    "stock": 150
  },
  {
    "_id": ObjectId("507f191e810c19729de860ea"),
    "name": "Gadget",
    "price": 49.50,
    "stock": 75
  }
]

Example 1 — Convert Number to String

Turn the numeric stock field into a string:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      stock: 1,
      stockText: { $toString: "$stock" }
    }
  }
])

How It Works

$toString converts the number 150 to the string "150". The original numeric field is unchanged.

📈 Labels and Display

Build composite labels with $concat, display ObjectIds, and format for export.

Example 2 — Build a Label with $concat

Combine text and numbers into a readable label:

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

// "Widget — $29.99 (150 in stock)"
// "Gadget — $49.5 (75 in stock)"

How It Works

$concat requires all parts to be strings. Wrap numeric fields in $toString before concatenating with text.

Example 3 — Display ObjectId as Hex String

Convert _id to a readable hex string for export or APIs:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      idString: { $toString: "$_id" }
    }
  }
])

// _id: ObjectId("507f1f77bcf86cd799439011")
// → idString: "507f1f77bcf86cd799439011"

How It Works

This is the reverse of $toObjectId. Use $toString when sending IDs to external systems that expect text, and $toObjectId when parsing them back.

Example 4 — Convert Boolean to String

Turn boolean flags into readable text for reports:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      active: 1,
      activeText: { $toString: "$active" }
    }
  }
])

// active: true  → activeText: "true"
// active: false → activeText: "false"

How It Works

Booleans become the strings "true" or "false". For user-friendly labels, consider $cond instead (e.g. "Yes" / "No").

Example 5 — Build a SKU Code from Mixed Fields

Combine a prefix, category code, and numeric ID into a SKU string:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      sku: {
        $concat: [
          "SKU-",
          "$category",
          "-",
          { $toString: "$productNum" }
        ]
      }
    }
  }
])

// category: "WGT", productNum: 42
// → sku: "SKU-WGT-42"

How It Works

String fields can be used directly in $concat, but numeric fields like productNum must be wrapped in $toString first.

Bonus — String Group Key from ObjectId

Group documents by stringified _id for cross-collection reporting:

mongosh
db.orders.aggregate([
  {
    $group: {
      _id: { $toString: "$customerId" },
      orderCount: { $sum: 1 },
      total: { $sum: "$amount" }
    }
  }
])

How It Works

Converting ObjectId group keys to strings makes output easier to read in reports and JSON exports.

🚀 Use Cases

  • Building labels — combine text and numbers with $concat for display strings.
  • ObjectId display — export IDs as hex strings for APIs and reports.
  • Data export — convert all field types to strings for CSV or JSON output.
  • Composite keys — build SKU codes, reference numbers, and identifiers from mixed fields.
  • Debugging — inspect typed values as readable strings in pipeline output.

🧠 How $toString Works

1

MongoDB reads the expression

The input resolves from a field path, literal, or nested expression of any BSON type.

Input
2

Value is converted to text

MongoDB applies type-specific string formatting (decimal for numbers, hex for ObjectIds, ISO for dates).

Convert
3

A string result is returned

The output can be used in $concat, displayed in reports, or exported as text.

Output
=

Readable text

Use in labels, exports, display fields, and string operations.

Conclusion

The $toString operator converts any BSON value to a string in MongoDB aggregation pipelines. It is essential for building text labels with $concat, displaying ObjectIds, and formatting data for export.

For the reverse conversion (string to ObjectId), use $toObjectId. For custom date formatting, use $dateToString. Next in the series: $toUpper.

💡 Best Practices

✅ Do

  • Wrap numeric fields in $toString before $concat
  • Use $toString on ObjectIds for API and export formats
  • Use $dateToString when you need custom date formatting
  • Keep original typed fields when you still need numeric operations
  • Pair with $toObjectId for round-trip ID conversion

❌ Don’t

  • Pass numbers directly to $concat without $toString
  • Use $toString on dates when you need a specific format (use $dateToString)
  • Assume "true"/"false" strings are user-friendly (use $cond for labels)
  • Forget that null input returns null
  • Replace numeric fields when you still need to sort or calculate on them

Key Takeaways

Knowledge Unlocked

Five things to remember about $toString

Use these points when converting values to strings in MongoDB.

5
Core concepts
📝 02

{ $toString: x }

One argument.

Syntax
🔗 03

$concat

Build labels.

Pairing
🛠 04

ObjectId

ID to hex.

Usage
05

vs $dateToString

Dates: use that.

Compare

❓ Frequently Asked Questions

$toString converts a value to a string inside an aggregation pipeline. It works on numbers, dates, ObjectIds, booleans, and other BSON types.
The syntax is { $toString: <expression> }. The expression can be a field reference like "$score", a literal, or any value you want to stringify.
Use $toString when building text labels with $concat, displaying ObjectIds as hex strings, formatting values for export, or combining mixed-type fields into a single string.
$toString converts any value to a string. $toObjectId converts a 24-character hex string to ObjectId. They are reverse operations for ID fields.
$toString returns null when the input is null. It does not throw an error for null input.

Continue the Operator Series

Move on to $toUpper for uppercase conversion, or review $concat for building text labels.

Next: $toUpper →

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