運算子 $toString 只會將指定表達式的值當做 String 傳回。
語法
{
$toString: < expression >
}
參數
| 參數 | Description |
|---|---|
expression |
要轉換成 String 值的指定值 |
範例
請參考商店集合中的此範例檔。
{
"_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 值轉換成 String 值
若要將緯度欄位的值從 Double 轉換成 String,請使用欄位上的 $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 值轉換成 String 值
若要將 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" |
| 任何 Double、Int、Long 或 Decimal 值。 例如,72 | 輸出:>「72」 |
| 任何 ObjectId 值。 例如,ObjectId(“b010763193704acdaafa8ac3”) | 輸出 -> "b010763193704acdaafa8ac3" |