运算符 $toDecimal 将输入表达式转换为十进制值。 Long、Double 或 Int 值只是转换为十进制数据类型,而十进制值按原样返回。 布尔值为 true 转换为 1,而布尔值为 false 转换为 0。 最后,ISODates 转换为与 ISODate 值表示的 1970 年 1 月 1 日以来的毫秒数相对应的十进制值。
Syntax
{
$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')"
}
]
相关内容
- 查看用于 从 MongoDB 迁移到 Azure DocumentDB 的选项。
- 详细了解 与 MongoDB 的功能兼容性。