AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

$toString(演算子)

$toString

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

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

{ $toString: <expression>}

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

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

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

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

入力タイプ
動作

ブール値

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

Double

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

小数点

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

整数

整数値を文字列として返します。

Long

long 値を文字列として返します。

ObjectId

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

文字列

何も起こりません。文字列値を返します。

日付

日付を文字列値として返します。

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

例
結果

{$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"

次のドキュメントを使用してコレクション 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 を使用します。

このページを評価

項目一覧