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( [
{
_id: 1</

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

被折叠的 条评论
为什么被折叠?



