你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
适用对象: MongoDB vCore
运算符 $toLong
将指定的值转换为 Long 值。
语法
运算符的 $toLong
语法为:
{ "$toLong": <expression> }
参数
参数 | DESCRIPTION |
---|---|
expression |
要转换为长值的指定值 |
例子
请查看 StoreData 数据库中 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 值转换为 Long 值
双精度值被截断并作为 Long 值返回
db.stores.aggregate([
{
"$match": {
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d"
}
},
{
"$project": {
"originalLatitude": "$location.lat",
"latitudeAsLong": {
"$toLong": "$location.lat"
}
}
}])
示例 2:将字符串值转换为 Long 值
如果字符串已是长值的字符串表示形式,则可以将其转换为 Long 值。
在此查询中,字符串“72”可以转换为长值。
db.stores.aggregate([
{
"$match": {
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d"
}
},
{
"$project": {
"originalLatitude": "$location.lat",
"latitudeAsLong": {
"$toLong": {
"$toString": "72"
}
}
}
}
])
这两个查询都返回以下结果
{
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
"originalLatitude": 72.8377,
"latitudeAsLong": Long('72')
}
此表根据输入值的数据类型来描述$toLong运算符的预期行为。
值类型 | 行为/输出 |
---|---|
布尔值为真 | 输出 -> Long(“1”) |
布尔值假 | 输出 -> Long(“1”) |
倍数值 例如,72.0 | 输出 -> Long(“72”) |
长值的字符串表示形式。 例如,“72” | 输出 -> Long(“72”) |
双精度值的字符串表示形式。 例如,“72.0” | 输出 -> 错误 |
空值 | 输出 -> null |