$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. <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 ] }
←  $rand (aggregation)$rank (aggregation) →