文档菜单
文档首页
/
MongoDB 手册
/ / /

$toLong (聚合查询)

本页内容

  • 定义
  • 行为
  • 示例
$toLong

将值转换为长整型。如果值无法转换为长整型,$toLong 将产生错误。如果值是 null 或不存在,$toLong 返回 null。

$toLong 语法如下

{
$toLong: <expression>
}

$toLong 可以接受任何有效的表达式.

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

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

提示

另请参阅

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

输入类型
行为
布尔值
对于 false 返回 Long(0)。
对于 true 返回 Long(1)。
双精度浮点数

返回截断值。

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

不能将截断值小于长整型最小值或大于长整型最大值的双精度浮点值转换为长整型。

十进制

返回截断值。

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

不能将截断值小于长整型最小值或大于长整型最大值的十进制值转换为长整型。

整型
返回整型值作为长整型。
长整型
无操作。返回长整型值。
字符串

返回字符串的数值。

字符串值必须是十进制长整型(例如 "-5""123456")。

无法将浮点数、十进制数或非十进制数(例如 "-5.0""0x6400")的字符串值转换为其他类型。

日期
将日期转换为自纪元以来的毫秒数。

以下表格列出了一些转换为长整型的示例

示例
结果
{ $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 转换为长整型

// 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

本页内容