MongoDB 4.0から、$toStringを使用できます 値を文字列に変換するための集計パイプライン演算子。
例
typesというコレクションがあるとします。 次のドキュメントが含まれています:
{
"_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")
}
$toStringを使用できます これらすべてのタイプを文字列に変換する演算子。入力が文字列の場合は、単に文字列を返します。
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() 結果:
{
"objectId" : "60123a54c8eb4369cf6ad9d6",
"double" : "123.75",
"string" : "123",
"boolean" : "true",
"date" : "2020-12-31T23:30:15.123Z",
"integer" : "123",
"long" : "123",
"decimal" : "123.75"
} エラー
エラーが発生した場合は、$convertを使用してみてください $toStringの代わりに演算子 。 $convert 演算子を使用すると、集計操作全体に影響を与えることなくエラーを処理できます。
$toString 演算子は、$convertを使用するのと同じです 値を文字列に変換する演算子。
$convertの使用例を次に示します。 日付を文字列に変換するには::
db.types.aggregate(
[
{
$project:
{
_id: 0,
result:
{
$convert: {
input: "$date",
to: "string",
onError: "An error occurred",
onNull: "Input was null or empty"
}
}
}
}
]
) 結果:
{ "result" : "2020-12-31T23:30:15.123Z" }
MongoDB $convertを参照してください その他の例については。