運算子 $toDecimal 會將輸入表達式轉換成十進位值。 Long、Double 或 Int 值只會轉換成 Decimal 數據類型,而十進位值會依原樣傳回。 true 的布爾值會轉換成 1,而布爾值 false 則轉換成 0。 最後,ISODates 會轉換成 Decimal 值,其對應於 ISODate 值所代表自 1970 年 1 月 1 日起的毫秒數。
語法
{
$toDecimal: < expression >
}
參數
| 參數 | Description |
|---|---|
expression |
要轉換成十進位值的指定值 |
範例
請參考商店集合中的此範例檔。
{
"_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 值轉換成十進位值
若要將緯度欄位的值從雙精度浮點數轉換成十進位值,請使用 $toDecimal 運算元執行查詢,以進行轉換。
db.stores.aggregate([{
$match: {
_id: "b0107631-9370-4acd-aafa-8ac3511e623d"
}
}, {
$project: {
originalLatitude: "$location.lat",
latitudeAsDecimal: {
$toDecimal: "$location.lat"
}
}
}])
此查詢會傳回下列結果:
[
{
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
"originalLatitude": 72.8377,
"latitudeAsDecimal": "Decimal128('72.8377000000000')"
}
]
範例 2:將 ISODate 值轉換成十進位值
若要將 ISODate 轉換成十進位值,請在值上使用 $toDecimal 運算符執行查詢,以進行轉換。
db.stores.aggregate([{
$match: {
_id: "b0107631-9370-4acd-aafa-8ac3511e623d"
}
}, {
$project: {
dateAsDecimal: {
$toDecimal: ISODate("2025-01-06T00:00:00.000Z")
}
}
}])
此查詢會傳回下列結果:
[
{
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
"dateAsDecimal": "Decimal128('1736121600000')"
}
]