$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通过将起始编号连续递增指定的步长值,直到但不包括终点,从而从指定的起始编号生成序列。

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

{ $range: [ <start>, <end>, <non-zero step> ] }
OperandDescription描述
<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. <start><end>参数是必需的,必须是整数。The <non-zero step> argument is optional, and defaults to 1 if omitted.<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 ] }