0
0
MongoDBquery~5 mins

Type conversion expressions ($toInt, $toString) in MongoDB

Choose your learning style9 modes available
Introduction

Type conversion expressions help change data from one type to another, like turning text into numbers or numbers into text. This is useful when you want to work with data in a specific way.

When you have a number stored as text and want to do math with it.
When you want to display a number as text for easier reading.
When combining different data types in one field and need them to match.
When filtering or sorting data that is stored as strings but should be numbers.
When preparing data for reports that require specific data types.
Syntax
MongoDB
{ $toInt: <expression> } or { $toString: <expression> }

$toInt converts the value to an integer number.

$toString converts the value to a string (text).

Examples
Converts the string "123" to the number 123.
MongoDB
{ $toInt: "123" }
Converts the number 456 to the string "456".
MongoDB
{ $toString: 456 }
Converts the value in the field price to an integer.
MongoDB
{ $toInt: "$price" }
Converts the value in the field quantity to a string.
MongoDB
{ $toString: "$quantity" }
Sample Program

This query takes the price field from each product, converts it to an integer and also to a string, and shows both in the result.

MongoDB
db.products.aggregate([
  {
    $project: {
      name: 1,
      priceAsInt: { $toInt: "$price" },
      priceAsString: { $toString: "$price" }
    }
  }
])
OutputSuccess
Important Notes

If the value cannot be converted, $toInt returns null.

Use these conversions to avoid errors when mixing data types in queries.

Summary

$toInt changes values to whole numbers.

$toString changes values to text.

These help make data easier to work with in different situations.