Docs Menu
Docs Home
/ /

$toString(演算子)

$toString

値を string に変換します。 値を string に変換できない場合は、 $toStringがエラーになります。 値が null または欠落している場合、 $toStringは null を返します。

$toString の構文は次のとおりです。

{
$toString: <expression>
}

$toStringは任意の有効な式を受け入れます。

$toString は次の $convert 式の省略形です。

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

Tip

  • $convert

  • $dateToString

次の表に、文字列に変換できる入力タイプを示します。

入力タイプ
動作

配列

Array を string として返します。

バージョン8.3の新機能

BinData

BinData が UUID の場合、 は UUID を string として返します。それ以外の場合、 は base64 でエンコードされた string の値を返します。

ブール値

ブール値を文字列として返します。

日付

Date を string として返します。

小数点

Decimal 値を string として返します。

Double

Double 値を string として返します。

整数

Integer 値を string として返します。

Long

Long 値を string として返します。

Max key

MaxKey を string として返します。

バージョン8.3の新機能

MinKey

MinKey を string として返します。

バージョン8.3の新機能

オブジェクト

オブジェクトを string として返します。

バージョン8.3の新機能

ObjectId

ObjectId 値を16進数文字列として返します。

正規表現

Regular Expression を string として返します。

バージョン8.3の新機能

文字列

操作はありません 。string 値を返します。

タイムスタンプ

Timestamp を string として返します。

バージョン8.3の新機能

Tip

10 以外の基数で文字列を変換するには、$convertbase オプションを併用します。

次の表に、文字列値への変換の例をいくつか示します。

結果

{ $toString: true }

"true"

{ $toString: false }

"false"

{ $toString: 2.5 }

"2.5"

{ $toString: Int32(2) }

"2"

{ $toString: Long(1000) }

"1000"

{ $toString: ObjectId("5ab9c3da31c2ab715d421285") }

"5ab9c3da31c2ab715d421285"

{ $toString: ISODate("2018-03-27T16:58:51.538Z") }

"2018-03-27T16:58:51.538Z"

{ $toString: BinData(4, "hn3f") }

"hn3f"

{ $toString: /^ABC/i }

"/^ABC/i"

バージョン8.3の新機能

{ $toString: new Timestamp(1565545664, 1) }

"Timestamp(1565545664, 1)"

バージョン8.3の新機能

{ $toString: [["pizza", {type: "cheese"}]] }

"[\"pizza\",{\"type\":\"cheese\"}]"

バージョン8.3の新機能

{ $toString: {pizza: {type: "cheese"}} }

"{\"pizza\":{\"type\":\"cheese\"}}"

バージョン8.3の新機能

{ $toString: MinKey }

"MinKey"

バージョン8.3の新機能

{ $toString: MaxKey }

"MaxKey"

バージョン8.3の新機能

次のドキュメントを使用してコレクション orders を作成します。

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 },
] )

orders コレクションに対する次の集計操作では、文字列値で並べ替える前に zipcode を文字列に変換します。

// 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
] )

この操作により、次のドキュメントが返されます。

{
_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'
}

注意

変換操作でエラーが発生した場合、集計操作は停止し、エラーがスローされます。この動作をオーバーライドするには、代わりに $convert を使用します。

戻る

$topN

項目一覧