Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$toLong(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$toLong

将值转换为长整型。如果该值无法转换为长整型,则 $toLong出错。如果值为 null 或缺失,则$toLong返回 null。

$toLong 通过以下语法实现:

{
$toLong: <expression>
}

$toLong可采用任何有效表达式。

$toLong是以下$convert表达式的简写:

{ $convert: { input: <expression>, to: "long" } }

提示

另请参阅:

下表列出了可转换为十进制值的输入类型:

下表列出了可转换为长整型的输入类型:

输入类型
行为
布尔
返回 Long(0) 以表示 false
对于 true,将返回 Long(1)。
双精度

返回截断后的值。

截断后的双精度值必须介于长整型值的最小值与最大值之间。

如果双精度值的截断值小于最小长值或大于最大长值,则无法转换该双精度值。

Decimal 数据类型

返回截断后的值。

截断后的十进制值必须介于长整型值的最小值与最大值之间。

如果某一十进制数值的截断值小于最小长整型值或大于最大长整型值,则无法转换该十进制数值。

整型
以 long 形式返回整数值。
长整型
不操作。返回长整型值。
字符串

返回字符串的数值。

字符串值必须以 10 为基长(例如 "-5""123456")。

您无法转换浮点数、十进制数或非以 10 为基数的字符串值(例如 "-5.0""0x6400")

Date
将“日期”转换为自纪元起的毫秒数。

下表列出了转换为长整型值的部分示例:

例子
结果
{ $toLong: true }
Long("1")
{ $toLong: false }
Long("0")
{ $toLong: 1.99999 }
Long("1")
{ $toLong: NumberDecimal("5.5000") }
Long("5")
{ $toLong: NumberDecimal("9223372036854775808.0") }
错误
{ $toLong: NumberInt(8) }
Long(8)
{ $toLong: ISODate("2018-03-26T04:38:28.044Z") }
Long("1522039108044")
{ $toLong: "-2" }
Long("2")
{ $toLong: "2.5" }
错误
{ $toLong: null }
null

使用以下文档创建集合 orders

db.orders.insertMany( [
{ _id: 1, item: "apple", qty: NumberInt(5) },
{ _id: 2, item: "pie", qty: "100" },
{ _id: 3, item: "ice cream", qty: NumberLong("500") },
{ _id: 4, item: "almonds", qty: "50" },
] )

orders 集合上的以下聚合操作会在按值排序之前将 qty 转换为 long:

// Define stage to add convertedQty field with converted qty value
qtyConversionStage = {
$addFields: {
convertedQty: { $toLong: "$qty" }
}
};
// Define stage to sort documents by the converted qty values
sortStage = {
$sort: { "convertedQty": -1 }
};
db.orders.aggregate( [
qtyConversionStage,
sortStage
])

该操作将返回以下文档:

{ _id: 3, item: 'ice cream', qty: Long("500"), convertedQty: Long("500") },
{ _id: 2, item: 'pie', qty: '100', convertedQty: Long("100") },
{ _id: 4, item: 'almonds', qty: '50', convertedQty: Long("50") },
{ _id: 1, item: 'apple', qty: 5, convertedQty: Long("5") }

注意

如果转换操作遇到错误,聚合操作会停止并抛出错误。要覆盖此行为,请改为使用 $convert

← $toInt(聚合)

在此页面上