定義
動作
次の表に、文字列に変換できる入力タイプを示します。
入力タイプ | 動作 |
|---|---|
配列 | を バージョン8.3の新機能。 |
BinData |
|
ブール値 | ブール値を string として返します。 |
日付 | を |
小数点 |
|
Double |
|
整数 |
|
Long |
|
Max key | を バージョン8.3の新機能。 |
MinKey | を バージョン8.3の新機能。 |
オブジェクト | オブジェクトを string として返します。 バージョン8.3の新機能。 |
ObjectId |
|
正規表現 | を バージョン8.3の新機能。 |
文字列 | 操作はありません 。 string 値を返します。 |
タイムスタンプ | を バージョン8.3の新機能。 |
Tip
10$convert以外の基数で文字列を変換するには、 とbase オプションを併用します。
次の表に、文字列値への変換の例をいくつか示します。
例 | 結果 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
バージョン8.3の新機能。 |
|
バージョン8.3の新機能。 |
|
バージョン8.3の新機能。 |
|
バージョン8.3の新機能。 |
|
バージョン8.3の新機能。 |
|
バージョン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 を使用します。