MongoDB聚合运算符:$toLong

MongoDB聚合运算符:$toLong

文章目录

  • [MongoDB聚合运算符:toLong](#MongoDB聚合运算符:toLong)

$toLong聚合运算符将指定的值转换为长整数类型。如果指定的值为空或缺失,则返回null;如果值无法被转换为长整数,则报错。

语法

js 复制代码
{
   $toLong: <expression>
}

$toLong接受任何有效的表达式。

$toLong$convert表达式的简写形式:

js 复制代码
{ $convert: { input: <expression>, to: "long" } }

使用

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

输入类型 规则
Boolean 对于True,返回Long(1),对于False返回Long(0)
Decimal 返回截断值。截断的小数值必须在长整数的最小值和最大值范围内。如果截断值小于最小长整数值或大于最大长整数值,则无法转换
Double 返回截断值。截断的双数值必须在长整数的最小值和最大值范围内。如果截断值小于最小长整数值或大于最大长整数值,则无法转换
Integer 以长整数返回整数值
Long 直接返回
String 将字符串转换为长整数返回,但字符串表示的必须是10进制的长整数比如"-5"、"1233",非10进制的会报错,如:"0x3343"
Date 返回自与日期值对应的纪元以来的毫秒数

下表列出了一些转换为长整数的示例:

示例 结果
$toLong: true Long("1")
$toLong: false Long("0")
$toLong: 1.99999 Long("1")
$toLong: NumberDecimal("5.5000") Long("5")
$toLong: NumberDecimal("9223372036000.000") Error
$toLong: NumberInt(8) Long(8)
$toLong: ISODate("2018-03-26T04:38:28.044Z") Long("1522039108044")
$toLong: "-2" Long("-2")
$toLong: "2.5" Error
$toLong: null null

举例

使用下面的脚本创建orders集合:

js 复制代码
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" },
] )

下面的聚合操将qty集转换为长整数,然后进行排序:

js 复制代码
// 定义阶段,将qty转换为长整数

qtyConversionStage = {
   $addFields: {
      convertedQty: { $toLong: "$qty" }
   }
};

// 定义阶段,基于转换后的字段convertedQty进行排序

sortStage = {
   $sort: { "convertedQty": -1 }
};


db.orders.aggregate( [
   qtyConversionStage,
   sortStage
])

执行的结果为:

js 复制代码
{ _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") }
相关推荐
LucianaiB43 分钟前
【金仓数据库征文】_AI 赋能数据库运维:金仓KES的智能化未来
运维·数据库·人工智能·金仓数据库 2025 征文·数据库平替用金仓
时序数据说1 小时前
时序数据库IoTDB在航空航天领域的解决方案
大数据·数据库·时序数据库·iotdb
.生产的驴1 小时前
SpringBoot 封装统一API返回格式对象 标准化开发 请求封装 统一格式处理
java·数据库·spring boot·后端·spring·eclipse·maven
AnsenZhu1 小时前
2025年Redis分片存储性能优化指南
数据库·redis·性能优化·分片
oydcm2 小时前
MySQL数据库概述
数据库·mysql
oioihoii2 小时前
C++23中if consteval / if not consteval (P1938R3) 详解
java·数据库·c++23
带娃的IT创业者2 小时前
《AI大模型趣味实战》基于RAG向量数据库的知识库AI问答助手设计与实现
数据库·人工智能
追逐时光者2 小时前
MongoDB从入门到实战之Docker快速安装MongoDB
后端·mongodb
husterlichf3 小时前
MYSQL 常用数值函数 和 条件函数 详解
数据库·sql·mysql
我的golang之路果然有问题3 小时前
快速了解redis,个人笔记
数据库·经验分享·redis·笔记·学习·缓存·内存