$toString (aggregation)

Definition

  • $toString

New in version 4.0.

Converts a value to a string. If the value cannot be convertedto a string, $toString errors. If the value is null ormissing, $toString returns null.

$toString has the following syntax:

  1. {
  2. $toString: <expression>
  3. }

The $toString takes any valid expression.

The $toString is a shorthand for the following$convert expression:

  1. { $convert: { input: <expression>, to: "string" } }

See also

$convert and $dateToString

Behavior

The following table lists the input types that can be converted to astring:

Input TypeBehavior
BooleanReturns the boolean value as a string.
DoubleReturns the double value as a string.
DecimalReturns the decimal value as a string.
IntegerReturns the integer value as a string.
LongReturns the long value as a string.
ObjectIdReturns the ObjectId value as a hexadecimal string..
StringNo-op. Returns the string value.
DateReturns the date as a string.

The following table lists some conversion to string examples:

ExampleResults
{$toString: true}“true”
{$toString: false}“false”
{$toString: 2.5}“2.5”
{$toString: NumberInt(2)}“2”
{$toString: NumberLong(1000)}“1000”
{$toString: ObjectId("5ab9c3da31c2ab715d421285")}“5ab9c3da31c2ab715d421285”
{$toString: ISODate("2018-03-27T16:58:51.538Z")}“2018-03-27T16:58:51.538Z”

Example

Create a collection orders with the following documents:

  1. db.orders.insert( [
  2. { _id: 1, item: "apple", qty: 5, zipcode: 12345 },
  3. { _id: 2, item: "pie", qty: 10, zipcode: 11111 },
  4. { _id: 3, item: "ice cream", zipcode: "12345" },
  5. { _id: 4, item: "almonds", qty: 2, zipcode: "12345-0030" },
  6. ])

The following aggregation operation on the orders collectionconverts the zipcode to string before sorting by the string value:

  1. // Define stage to add convertedZipCode field with the converted zipcode value
  2.  
  3. zipConversionStage = {
  4. $addFields: {
  5. convertedZipCode: { $toString: "$zipcode" }
  6. }
  7. };
  8.  
  9. // Define stage to sort documents by the converted zipcode
  10.  
  11. sortStage = {
  12. $sort: { "convertedZipCode": 1 }
  13. };
  14.  
  15. db.orders.aggregate( [
  16. zipConversionStage,
  17. sortStage
  18. ])

The operation returns the following documents:

  1. { "_id" : 2, "item" : "pie", "qty" : 10, "zipcode" : 11111, "convertedZipCode" : "11111" }
  2. { "_id" : 1, "item" : "apple", "qty" : 5, "zipcode" : 12345, "convertedZipCode" : "12345" }
  3. { "_id" : 3, "item" : "ice cream", "zipcode" : "12345", "convertedZipCode" : "12345" }
  4. { "_id" : 4, "item" : "almonds", "qty" : 2, "zipcode" : "12345-0030", "convertedZipCode" : "12345-0030" }

Note

If the conversion operation encounters an error, the aggregationoperation stops and throws an error. To override this behavior, use$convert instead.