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'
}

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

相关推荐
DemonAvenger28 分钟前
MySQL海量数据快速导入导出技巧:从实战到优化
数据库·mysql·性能优化
薛定谔的算法17 小时前
phoneGPT:构建专业领域的检索增强型智能问答系统
前端·数据库·后端
Databend18 小时前
Databend 亮相 RustChinaConf 2025,分享基于 Rust 构建商业化数仓平台的探索
数据库
得物技术19 小时前
破解gh-ost变更导致MySQL表膨胀之谜|得物技术
数据库·后端·mysql
似水流年流不尽思念1 天前
MongoDB 有哪些索引?适用场景?
后端·mongodb
Raymond运维1 天前
MariaDB源码编译安装(二)
运维·数据库·mariadb
沢田纲吉1 天前
🗄️ MySQL 表操作全面指南
数据库·后端·mysql
RestCloud2 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud2 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence2 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库