$split (aggregation)

在本页面

3.4 版的新功能。

Definition

$split具有以下运算符表达式语法

{ $split: [ <string expression>, <delimiter> ] }
Field Type Description
string expression string 要分割的字符串。 string expression可以是任何有效的expression,只要它可以解析为字符串即可。有关表达式的更多信息,请参见Expressions
delimiter string 分割字符串表达式时使用的定界符。 delimiter可以是任何有效的expression,只要它解析为字符串即可。

Behavior

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

Example Results
{ $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"

Example

名为deliveries的集合包含以下文档:

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

后续聚合操作的目标是找到每个 State 的交货总量,并按降序对列表进行排序。它具有五个管道阶段:

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 }
首页