From MongoDB 4.0, you can use the $toString aggregation pipeline operator to convert a value to a string.
Example
Suppose we have a collection called types and it contains the following document:
{
"_id" : ObjectId("60123a54c8eb4369cf6ad9d6"),
"double" : 123.75,
"string" : "123",
"boolean" : true,
"date" : ISODate("2020-12-31T23:30:15.123Z"),
"integer" : 123,
"long" : NumberLong(123),
"decimal" : NumberDecimal("123.75")
}
We can use the $toString operator to convert all those types to a string. If the input is a string, then it simply returns the string.
db.types.aggregate(
[
{
$project:
{
_id: 0,
objectId: { $toString: "$_id" },
double: { $toString: "$double" },
string: { $toString: "$string" },
boolean: { $toString: "$boolean" },
date: { $toString: "$date" },
integer: { $toString: "$integer" },
long: { $toString: "$long" },
decimal: { $toString: "$decimal" }
}
}
]
).pretty()
Result:
{
"objectId" : "60123a54c8eb4369cf6ad9d6",
"double" : "123.75",
"string" : "123",
"boolean" : "true",
"date" : "2020-12-31T23:30:15.123Z",
"integer" : "123",
"long" : "123",
"decimal" : "123.75"
}
Errors
If you encounter errors, try using the $convert operator instead of $toString. The $convert operator allows you to handle errors without affecting the whole aggregation operation.
The $toString operator is the equivalent of using the $convert operator to convert a value to a string.
Here’s an example of using $convert to convert a date to a string::
db.types.aggregate(
[
{
$project:
{
_id: 0,
result:
{
$convert: {
input: "$date",
to: "string",
onError: "An error occurred",
onNull: "Input was null or empty"
}
}
}
}
]
)
Result:
{ "result" : "2020-12-31T23:30:15.123Z" }
See MongoDB $convert for more examples.