MongoDB聚合运算符:$split

本文详细解释了MongoDB中的$split聚合运算符,展示了如何使用分隔符将字符串拆分成数组,以及在实际项目中如何运用它来处理和汇总数据。通过实例演示了如何在deliveries集合上应用此运算符来计算各州的交付总量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MongoDB聚合运算符:$split


$split聚合运算符根据分隔符将字符串分割成子串数组。 $split会移除分隔符,并返回作为数组元素的子串。如果在字符串中找不到分隔符, $split会把原始字符串作为数组的唯一元素返回。

语法

{
    $split: [ <string expression>, <delimiter> ] }

参数说明:

  • <string expression>:字符串类型,要分割的字符串表达式。
  • delimiter:字符串类型,分割字符串时使用的分隔符,可以是任何字符串表达式。

使用

$split 运算符返回一个数组,<string expression><delimiter>必须是字符串,否则操作将失败并出现错误。

例子 结果
{ $split: [ "June-15-2013", "-" ] } [ "June", "15", "2013" ]
{ $split: [ "banana split", "a" ] } [ "b", "n", "n", " split" ]
{ $split: [ "Hello World", " " ] } [ "Hello", "World" ]
{ $split: [ "astronomical", "astro" ] } [ "", "nomical" ]
{ $split: [ "pea green boat", "owl" ] } [ "pea green boat" ]
{ $split: [ "headphone jack", 7 ] } 报错信息:"$split requires an expression that evaluates to a string as a second argument, found: double"
{ $split: [ "headphone jack", /jack/ ] } 报错信息:"$split requires an expression that evaluates to a string as a second argument, found: regex"

举例

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

db.deliveries.insertMany( [
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

原子星

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

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

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

打赏作者

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

抵扣说明:

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

余额充值