$toString演算子は、指定した式の値を文字列として返します。
構文
{
$toString: < expression >
}
パラメーター
| パラメーター | Description |
|---|---|
expression |
文字列値に変換する指定した値 |
例示
stores コレクションのこのサンプル ドキュメントについて考えてみましょう。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
例 1: Double 値を文字列値に変換する
緯度フィールドの値を Double から文字列に変換するには、フィールドの $toString 演算子を使用してクエリを実行し、変換を行います。
db.stores.aggregate([{
$match: {
_id: "b0107631-9370-4acd-aafa-8ac3511e623d"
}
}, {
$project: {
originalLatitude: "$location.lat",
latitudeAsString: {
$toString: "$location.lat"
}
}
}])
このクエリは、次の結果を返します。
[
{
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
"originalLatitude": 72.8377,
"latitudeAsString": "72.8377"
}
]
例 2: Int 値を文字列値に変換する
totalSales フィールドの値を Int から String に変換するには、フィールドの $toString 演算子を使用してクエリを実行し、変換を行います。
db.stores.aggregate([{
$match: {
_id: "b0107631-9370-4acd-aafa-8ac3511e623d"
}
}, {
$project: {
originalTotalSales: "$sales.totalSales",
totalSalesAsString: {
$toString: "$sales.totalSales"
}
}
}])
このクエリは、次の結果を返します。
[
{
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
"originalTotalSales": 9366,
"totalSalesAsString": "9366"
}
]
次の表は、入力値のデータ型に基づいて、$toString演算子の予期される動作を示しています。
| バリュータイプ | Behavior/Output |
|---|---|
| ブール値 真 | 出力 -> "true" |
| ブール値 false | 出力 -> "false" |
| Double、Int、Long、Decimal のいずれかの値。 たとえば、72 | 出力 -> "72" |
| 任意の ObjectId 値。 たとえば、ObjectId("b010763193704acdaafa8ac3") | 出力 -> "b010763193704acdaafa8ac3" |