$split (聚合)
定义
$split
基于分隔符将字符串分割成子字符串数组。
$split
移除分隔符,并将结果子字符串作为数组的元素返回。如果字符串中未找到分隔符,$split
将返回原始字符串作为数组的唯一元素。$split
具有以下操作表达式语法:{ $split: [ <string expression>, <delimiter> ] }
行为
的$split
运算符返回一个数组。输入的<字符串表达式>
和<分隔符>
都必须是字符串。否则,操作将因错误而失败。
示例 | 结果 | ||
---|---|---|---|
|
| ||
|
| ||
|
| ||
|
| ||
|
| ||
{ $split: [ "耳机插孔", 7 ] } | 带有消息的错误
| ||
{ $split: [ "耳机插孔", /jack/ ] } | 带有消息的错误
|
示例
名为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 } ] )
以下聚合操作的目标是找出每个州的总运量并按降序排列列表。它有五个管道阶段
$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 } ]