On this page本页内容
$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> ] }
<start> | |
<end> | |
<non-zero step> |
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
。
{ $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 ] |
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 ] }