$toString (Convert to String)
Last updated: 2026-10-09
$toString (Convert to String)
$toString converts a value to a string. Numbers, dates, booleans, ObjectIds and more convert cleanly; null stays null. Typical uses: turning numbers into strings before $concat, exposing ObjectIds to frontends as strings, or unifying display formats. It is the $convert shortcut for to: string. Date-to-string output has no format control — use $dateToString when a specific format is required.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $toString: <expression> }
⚙️ Parameters
| expression | A number, date, boolean, ObjectId, or other value. |
|---|
Returns:A string; null when the input is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $toString: join a number into a label
db.products.aggregate([
{ $project: {
label: { $concat: ['SKU-', { $toString: '$skuNum' }] }
} }
])
Output:
{ '_id': 1, 'label': 'SKU-1001' }
📌 Notes
- Numbers, dates, booleans and ObjectIds all convert to strings
- null yields null; guard before concatenating
- Date-to-string output is fixed and uncontrollable; use $dateToString for custom formats
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QCan $concat join numbers directly?
ANo — convert with $toString first.
QWhat format do dates become?
AA fixed, uncontrollable format; use $dateToString for custom output.
QWhat happens with null?
AIt returns null; and $concat yields null entirely, so guard it.