Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$split(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$split

根据分隔符将字符串划分为子字符串数组。$split 会删除该分隔符,并将生成的子字符串作为数组的元素返回。如果在此字符串中未找到分隔符,$split 则会返回原始字符串以作为数组的唯一元素。

$split 采用以下运算符表达式语法

{ $split: [ <string expression>, <delimiter> ] }
字段
类型
说明
string expression
字符串
待分割的字符串。string expression 可以是任何有效的表达式,只要它解析为字符串即可。有关表达式的更多信息,请参阅表达式
delimiter
字符串
分割字符串表达式时使用的分隔符。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, city: "Berkeley, CA", qty: 648 },
{ _id: 2, city: "Bend, OR", qty: 491 },
{ _id: 3, city: "Kensington, CA", qty: 233 },
{ _id: 4, city: "Eugene, OR", qty: 842 },
{ _id: 5, city: "Reno, NV", qty: 655 },
{ _id: 6, city: "Portland, OR", qty: 408 },
{ _id: 7, city: "Sacramento, CA", qty: 574 }
] )

以下聚合操作的目标是查找每个州的交付(deliveries)总数量,并按降序对列表进行排序。它包含五个管道阶段:

  • $project 阶段生成包含两个字段的文档,即 qty(整数)和 city_state(数组)。$split 运算符通过拆分 city 字段,使用逗号后跟空格 (", ") 作为分隔符来创建字符串数组。

  • $unwind 阶段为 city_state 字段中的每个元素创建一个单独的记录。

  • $match 阶段会使用正则表达式过滤掉城市文档,只剩下包含省/市/自治区的文档。

  • $group 阶段会将所有状态分在一组,并对 qty 字段求和。

  • $sort 阶段按 total_qty 降序对结果排序。

db.deliveries.aggregate( [
{ $project: { city_state: { $split: ["$city", ", "] }, qty: 1 } },
{ $unwind: "$city_state" },
{ $match: { city_state: /[A-Z]{2}/ } },
{ $group: { _id: { state: "$city_state" }, total_qty: { $sum: "$qty" } } },
{ $sort: { total_qty: -1 } }
] )

操作返回以下结果:

[
{ _id: { state: "OR" }, total_qty: 1741 },
{ _id: { state: "CA" }, total_qty: 1455 },
{ _id: { state: "NV" }, total_qty: 655 }
]
← $sortArray(聚合)

在此页面上