MongoDB聚合运算符:$toString

MongoDB聚合运算符:$toString

文章目录

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

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

语法

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

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

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

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

使用

下表列出了可转换为字符串的类型:

输入类型 规则
Boolean 返回布尔值的字符串
Decimal 返回小数值的字符串
Double 返回双精度数的字符串
Integer 返回整数的字符串
Long 返回长整数的字符串
String 直接返回
ObjectId 返回ObjectId值的16进制字符串
Date 返回日期字符串

下表列出了一些转换为字符串的示例:

示例 结果
$toString: true "true"
$toString: false "false"
$toString: 2.5 "2.5"
$toString: NumberInt(2) "2"
$toString: NumberLong(1000) "1000"
$toString: NumberInt(8) Long(8)
$toString: ObjectId("5ab9c3da31c2ab715d421285") "5ab9c3da31c2ab715d421285"
$toString: ISODate("2018-03-27T16:58:51.538Z" "2018-03-27T16:58:51.538Z"

举例

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

js 复制代码
db.orders.insertMany( [
   { _id: 1, item: "apple",  qty: 5, zipcode: 93445 },
   { _id: 2, item: "almonds", qty: 2, zipcode: "12345-0030" },
   { _id: 3, item: "peaches",  qty: 5, zipcode: 12345 },
] )

下面的聚合操将zipcode集转换为字符串,然后进行排序:

js 复制代码
// 定义阶段,将zipcode转换为字符串

zipConversionStage = {
   $addFields: {
      convertedZipCode: { $toString: "$zipcode" }
   }
};

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

sortStage = {
   $sort: { "convertedZipCode": 1 }
};


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

执行的结果为:

js 复制代码
{
  _id: 3,
  item: 'peaches',
  qty: 5,
  zipcode: 12345,
  convertedZipCode: '12345'
},
{
  _id: 2,
  item: 'almonds',
  qty: 2,
  zipcode: '12345-0030',
  convertedZipCode: '12345-0030'
},
{
  _id: 1,
  item: 'apple',
  qty: 5,
  zipcode: 93445,
  convertedZipCode: '93445'
}

**注意:**如果转换操作遇到错误,聚合操作将停止并抛出错误。

相关推荐
数据知道25 分钟前
PostgreSQL 故障排查:如何找出数据库中最耗时的 SQL 语句
数据库·sql·postgresql
qq_124987075326 分钟前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计
枷锁—sha27 分钟前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全
Coder_Boy_31 分钟前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
Gain_chance37 分钟前
35-学习笔记尚硅谷数仓搭建-DWS层最近n日汇总表及历史至今汇总表建表语句
数据库·数据仓库·hive·笔记·学习
此生只爱蛋1 小时前
【Redis】主从复制
数据库·redis
马猴烧酒.1 小时前
【面试八股|JAVA多线程】JAVA多线程常考面试题详解
java·服务器·数据库
天天爱吃肉82182 小时前
跟着创意天才周杰伦学新能源汽车研发测试!3年从工程师到领域专家的成长秘籍!
数据库·python·算法·分类·汽车
大巨头2 小时前
sql2008 数据库分页语句
数据库
m0_715575342 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python