Definition
$toStringConverts 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:{ $toString: <expression> } The
$toStringtakes any valid expression.The
$toStringis a shorthand for the following$convertexpression:{ $convert: { input: <expression>, to: "string" } }
Behavior
The following table lists the input types that can be converted to a string:
Input Type | Behavior |
|---|---|
Array | Returns the New in version 8.3. |
BinData | Returns the |
Boolean | Returns the Boolean value as a string. |
Date | Returns the |
Decimal | Returns the |
Double | Returns the |
Integer | Returns the |
Long | Returns the |
MaxKey | Returns the New in version 8.3. |
MinKey | Returns the New in version 8.3. |
Object | Returns the object as a string. New in version 8.3. |
ObjectId | Returns the |
Regular Expression | Returns the New in version 8.3. |
String | No operation. Returns the string value. |
Timestamp | Returns the New in version 8.3. |
The following table lists some conversion to string examples:
Example | Results |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
New in version 8.3. |
|
New in version 8.3. |
|
New in version 8.3. |
|
New in version 8.3. |
|
New in version 8.3. |
|
New in version 8.3. |
Example
Create a collection orders with the following documents:
db.orders.insertMany( [ { _id: 1, item: "apple", qty: 5, zipcode: 93445 }, { _id: 2, item: "almonds", qty: 2, zipcode: "12345-0030" }, { _id: 3, item: "peaches", qty: 5, zipcode: 12345 }, ] )
The following aggregation operation on the orders collection
converts the zipcode to string before sorting by the string value:
// Define stage to add convertedZipCode field with the converted zipcode value zipConversionStage = { $addFields: { convertedZipCode: { $toString: "$zipcode" } } }; // Define stage to sort documents by the converted zipcode sortStage = { $sort: { "convertedZipCode": 1 } }; db.orders.aggregate( [ zipConversionStage, sortStage ] )
The operation returns the following documents:
{ _id: 3, item: 'peaches', qty: 5, zipcode: 12345, convertedZipCode: '12345' }, { _id: 2, item: 'almonds', qty: 2, zipcode: '12345-0030', convertedZipCode: '12345-0030' }, { _id: 1, item: 'apple', qty: 5, zipcode: 93445, convertedZipCode: '93445' }
Note
If the conversion operation encounters an error, the aggregation
operation stops and throws an error. To override this behavior, use
$convert instead.