- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $toString (aggregation)
$toString (aggregation)¶
On this page
Definition¶
-
$toString¶ New in version 4.0.
Converts a value to a string. If the value cannot be converted to a string,
$toStringerrors. If the value is null or missing,$toStringreturns null.$toStringhas the following syntax:The
$toStringtakes any valid expression.The
$toStringis a shorthand for the following$convertexpression:See also
Behavior¶
The following table lists the input types that can be converted to a string:
| Input Type | Behavior |
|---|---|
| Boolean | Returns the boolean value as a string. |
| Double | Returns the double value as a string. |
| Decimal | Returns the decimal value as a string. |
| Integer | Returns the integer value as a string. |
| Long | Returns the long value as a string. |
| ObjectId | Returns the ObjectId value as a hexadecimal string.. |
| String | No-op. Returns the string value. |
| Date | Returns the date as a string. |
The following table lists some conversion to string examples:
| Example | Results |
|---|---|
{$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:
The following aggregation operation on the orders collection
converts the zipcode to string before sorting by the string value:
The operation returns the following documents:
Note
If the conversion operation encounters an error, the aggregation
operation stops and throws an error. To override this behavior, use
$convert instead.