Docs HomeMongoDB Manual

$range (aggregation)

On this page本页内容

Definition定义

$range

Returns an array whose elements are a generated sequence of numbers. 返回一个数组,该数组的元素是生成的数字序列。$range generates the sequence from the specified starting number by successively incrementing the starting number by the specified step value up to but not including the end point.通过将起始数连续递增指定步长值直到但不包括终点,从指定起始数生成序列。

$range has the following operator expression syntax:具有以下运算符表达式语法

{ $range: [ <start>, <end>, <non-zero step> ] }
Operand运算数Description描述
<start>An integer that specifies the start of the sequence. 指定序列开始的整数。Can be any valid expression that resolves to an integer.可以是解析为整数的任何有效表达式
<end>An integer that specifies the exclusive upper limit of the sequence. 一个整数,用于指定序列的独占上限。Can be any valid expression that resolves to an integer.可以是解析为整数的任何有效表达式
<non-zero step>Optional.可选的。An integer that specifies the increment value. 指定增量值的整数。Can be any valid expression that resolves to a non-zero integer. 可以是解析为非零整数的任何有效表达式Defaults to 1.默认值为1。

Behavior行为

The <start> and <end> arguments are required and must be integers. The <non-zero step> argument is optional, and defaults to 1 if omitted.<start><end>参数是必需的,并且必须是整数。<non-zero step>参数是可选的,如果省略,则默认为1

Example示例Results结果
{ $range: [ 0, 10, 2 ] }[ 0, 2, 4, 6, 8 ]
{ $range: [ 10, 0, -2 ] }[ 10, 8, 6, 4, 2 ]
{ $range: [ 0, 10, -2 ] }[ ]
{ $range: [ 0, 5 ] }[ 0, 1, 2, 3, 4 ]

Example实例

The following example uses a collection called distances that lists cities along with their distance in miles from San Francisco.以下示例使用一个名为distances的集合,该集合列出了城市及其距离旧金山的英里数。

Documents in the distances collection:distances集合中的文档:

{ _id: 0, city: "San Jose", distance: 42 }
{ _id: 1, city: "Sacramento", distance: 88 }
{ _id: 2, city: "Reno", distance: 218 }
{ _id: 3, city: "Los Angeles", distance: 383 }

A bicyclist is planning to ride from San Francisco to each city listed in the collection and wants to stop and rest every 25 miles. 一名骑自行车的人计划从旧金山骑到该系列中列出的每个城市,并希望每25英里停下来休息一次。The following aggregation pipeline operation uses the $range operator to determine the stopping points for each trip.以下聚合管道操作使用$range运算符来确定每次跳闸的停止点。

db.distances.aggregate([{
$project: {
_id: 0,
city: 1,
"Rest stops": { $range: [ 0, "$distance", 25 ] }
}
}])

The operation returns the following:该操作返回以下内容:

{ "city" : "San Jose", "Rest stops" : [ 0, 25 ] }
{ "city" : "Sacramento", "Rest stops" : [ 0, 25, 50, 75 ] }
{ "city" : "Reno", "Rest stops" : [ 0, 25, 50, 75, 100, 125, 150, 175, 200 ] }
{ "city" : "Los Angeles", "Rest stops" : [ 0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375 ] }