MongoDB聚合运算符:$toString

MongoDB聚合运算符:$toString


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

语法

{
   $toString: <expression>
}

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

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

{ $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集合:

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集转换为字符串,然后进行排序:

// 定义阶段,将zipcode转换为字符串

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

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

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


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

执行的结果为:

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原子星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值