$range 연산자는 순차 정수 배열을 생성하는 데 사용됩니다. 이 연산자는 페이지 매김, 인덱싱 또는 테스트 데이터에 유용한 범위에서 숫자 배열을 만드는 데 도움이 됩니다.
문법
{
$range: [ <start>, <end>, <step> ]
}
매개 변수
| 매개 변수 | Description |
|---|---|
start |
범위의 시작 값(포함)입니다. |
end |
범위의 끝 값(배타적)입니다. |
step |
범위의 각 숫자 사이의 증분 값입니다(선택 사항, 기본값: 1). |
예시
스토어 컬렉션에서 이 샘플 문서를 고려합니다.
{
"_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
]
}
]