$toString

The `$toString` operator simply returns the value of the specified expression as a String.

Syntax

{
  $toString: <expression>
}

Parameters

expressionobjectrequired

The specified value to convert into a String value.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop",
  "location": { "lat": -89.2384 },
  "sales": { "totalSales": 75670 }
}

Convert a Double to String

Convert the latitude field from Double to String.

This query converts a numeric value to its string representation.

Query:

db.stores.aggregate([{
  $match: { _id: "b0107631-9370-4acd-aafa-8ac3511e623d" }
}, {
  $project: {
    originalLatitude: "$location.lat",
    latitudeAsString: { $toString: "$location.lat" }
  }
}])

Output:

[
  {
    "_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
    "originalLatitude": 72.8377,
    "latitudeAsString": "72.8377"
  }
]

Convert an Int to String

Convert the totalSales field from Int to String.

This query converts an integer to a string value.

Query:

db.stores.aggregate([{
  $match: { _id: "b0107631-9370-4acd-aafa-8ac3511e623d" }
}, {
  $project: {
    originalTotalSales: "$sales.totalSales",
    totalSalesAsString: { $toString: "$sales.totalSales" }
  }
}])

Output:

[
  {
    "_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
    "originalTotalSales": 9366,
    "totalSalesAsString": "9366"
  }
]

Related