$range演算子は、連続する整数の配列を生成するために使用されます。 この演算子は、範囲に数値配列を作成するのに役立ち、改ページ、インデックス作成、またはテスト データに役立ちます。
構文
{
$range: [ <start>, <end>, <step> ]
}
パラメーター
| パラメーター | Description |
|---|---|
start |
範囲の開始値 (両端を含む)。 |
end |
範囲の終了値 (排他)。 |
step |
範囲内の各数値の間の増分値 (省略可能、既定値は 1)。 |
例示
stores コレクションのこのサンプル ドキュメントについて考えてみましょう。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
例 1: 数値の範囲を生成する
このクエリでは、演算子を使用して 0 から 5 までの整数の配列を生成する方法を示します。この配列には左の境界が含まれますが、右側は除外されます。
db.stores.aggregate([{
$match: {
_id: "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6"
}
}, {
$project: {
rangeArray: {
$range: [0, 5]
}
}
}])
このクエリは、次の結果を返します。
[
{
"_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6",
"rangeArray": [
0,
1,
2,
3,
4
]
}
]
例 2: ステップ値を持つ数値の範囲を生成する
このクエリでは、演算子を使用して、0 から 18 までの偶数の配列を生成する方法を示します。
db.stores.aggregate([{
$match: {
_id: "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6"
}
}, {
$project: {
evenNumbers: {
$range: [0, 8, 2]
}
}
}])
このクエリの結果は次のようになります。
[
{
"_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6",
"rangeArray": [
0,
2,
4,
6
]
}
]