$indexOfArray 연산자는 배열에서 요소를 검색하고 요소의 첫 번째 발생 인덱스 반환에 사용됩니다. 요소를 찾을 수 없으면 반환됩니다 -1. 이 연산자는 배열 내에서 요소의 위치를 결정해야 하는 쿼리에 유용합니다. 예를 들어 목록에서 특정 값 또는 개체의 인덱스 찾기
문법
{
$indexOfArray: [ < array > , < searchElement > , < start > , < end > ]
}
매개 변수
| 매개 변수 | Description |
|---|---|
<array> |
요소를 검색할 배열입니다. |
<searchElement> |
배열에서 검색하는 요소입니다. |
<start> |
(선택 사항) 검색을 시작할 인덱스입니다. 생략하면 배열의 시작 부분에서 검색이 시작됩니다. |
<end> |
(선택 사항) 검색을 종료할 인덱스입니다. 생략하면 검색이 배열의 끝까지 진행됩니다. |
예시
스토어 컬렉션에서 이 샘플 문서를 고려합니다.
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
"location": {
"lat": 60.1441,
"lon": -141.5012
},
"staff": {
"totalStaff": {
"fullTime": 2,
"partTime": 0
}
},
"sales": {
"salesByCategory": [
{
"categoryName": "DJ Headphones",
"totalSales": 35921
}
],
"fullSales": 3700
},
"promotionEvents": [
{
"eventName": "Bargain Blitz Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 3,
"Day": 11
},
"endDate": {
"Year": 2024,
"Month": 2,
"Day": 18
}
},
"discounts": [
{
"categoryName": "DJ Turntables",
"discountPercentage": 18
},
{
"categoryName": "DJ Mixers",
"discountPercentage": 15
}
]
}
],
"tag": [
"#ShopLocal",
"#SeasonalSale",
"#FreeShipping",
"#MembershipDeals"
]
}
예제 1: 첫 번째 항목의 인덱스 찾기
이 쿼리는 컬렉션 전체의 배열 내에서 salesByCategory 특정 범주 이름("DJ Headphones")의 위치(인덱스)를 찾습니다.
db.stores.aggregate([
{
$project: {
index: {
$indexOfArray: [
"$sales.salesByCategory.categoryName",
"DJ Headphones"
]
}
}
},
// Limit the result to the first 3 documents
{ $limit: 3 }
])
이 쿼리는 다음 결과를 반환합니다.
[
{
"_id": "649626c9-eda1-46c0-a27f-dcee19d97f41",
"index": -1
},
{
"_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34",
"index": -1
},
{
"_id": "57cc4095-77d9-4345-af20-f8ead9ef0197",
"index": -1
}
]
예제 2: 범위에서 인덱스 찾기
이 쿼리는 특정 범위의 인덱스(3~5) 내에서 배열 내에서 promotionEvents "Bargain Blitz Days" 프로모션 이벤트의 위치를 찾고 일치하는 처음 세 개의 문서를 반환하는 작업과 함께 결과를 필터링합니다.
db.stores.aggregate([
// Step 1: Project the index of the "Bargain Blitz Days" event name within the specified range
{
$project: {
index: {
$indexOfArray: [
"$promotionEvents.eventName",
"Bargain Blitz Days",
3,
5
]
}
}
},
// Step 2: Match documents where index > 0
{
$match: {
index: { $gt: 0 }
}
},
// Limit the result to the first 3 documents
{ $limit: 3 }
])
이 쿼리는 다음 결과를 반환합니다.
[
{
"_id": "ced8caf0-051a-48ce-88d3-2935815261c3",
"index": 3
},
{
"_id": "509be7ce-539a-41b5-8fde-b85fb3ef3faa",
"index": 3
},
{
"_id": "d06e8136-9a7f-4b08-92c8-dc8eac73bad3",
"index": 3
}
]
관련 콘텐츠
- MongoDB에서 Azure DocumentDB로 마이그레이션하기 위한 옵션을 검토합니다.
- MongoDB와의 기능 호환성에 대해 자세히 알아보세요.