정의
$indexOfArray지정된 값의 발생을 배열에서 검색하고 첫 번째 발생의 배열 인덱스를 반환합니다. 배열 인덱스는 0부터 시작합니다.
$indexOfArrayhas the following operator expression syntax:{ $indexOfArray: [ <array expression>, <search expression>, <start>, <end> ] } 필드유형설명<array>배열
배열로 해석되는 한 모든 유효한 표현식 일 수 있습니다. 표현식에 대한 자세한 내용은 표현식을 참조하세요 .
If the array expression resolves to a value of
nullor refers to a field that is missing,$indexOfArrayreturnsnull.If the array expression does not resolve to an array or
nullnor refers to a missing field,$indexOfArrayreturns an error.<search value>문자열
<start>integer
선택 사항. 정수 또는 검색의 시작 인덱스 위치를 지정하는 정수(예: 2.0)로 표시할 수 있는 숫자입니다. 음수가 아닌 정수로 해석되는 유효한 표현식이 될 수 있습니다.
지정하지 않으면 검색의 시작 인덱스 위치는 문자열의 시작입니다.
<end>integer
Optional. An integer, or a number that can be represented as integers (such as 2.0), that specifies the ending index position for the search. Can be any valid expression that resolves to a non-negative integral number. If you specify a
<end>index value, you should also specify a<start>index value; otherwise,$indexOfArrayuses the<end>value as the<start>index value instead of the<end>value.지정하지 않으면 검색의 끝 인덱스 위치는 문자열의 끝입니다.
행동
If the <search expression> is found multiple times within the <array expression>, then $indexOfArray returns the index of the first <search expression> from the starting index position.
$indexOfArray returns null:
<array expression>이(가) null인 경우, 또는<array expression>이 입력 문서에 존재하지 않는 필드를 참조하는 경우
$indexOfArray 은(는) 오류를 반환합니다.
<array expression>배열이 아니고 null이 아닌 경우 또는<start>또는<end>가 음의 정수(또는 -5.0과 같이 음의 정수로 표시될 수 있는 값)인 경우
$indexOfArray returns -1:
<search expression>이 배열에 없는 경우, 또는
<start>가<end>보다 큰 숫자인 경우 또는<start>가 배열의 길이보다 큰 숫자인 경우.
예시 | 결과 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 오류 |
예시
이 예제에서는 이 inventory collection을 사용합니다.
db.inventory.insertMany( [ { _id: 0, items: [ "one", "two", "three" ] }, { _id: 1, items: [ 1, 2, 3 ] }, { _id: 2, items: [ 1, 2, 3, 2 ] }, { _id: 3, items: [ null, null, 2 ] }, { _id: 4, items: [ 2, null, null, 2 ] }, { _id: 5, items: null }, { _id: 6, amount: 3 } ] )
The following example uses $indexOfArray to find 2 in the items array:
db.inventory.aggregate( [ { $project: { index: { $indexOfArray: [ "$items", 2 ] } } } ] )
이 예시에서는 다음을 반환합니다.
각
items배열에서 값2에 대한 첫 번째 배열 인덱스(있는 경우)입니다. 배열 인덱스는0에서 시작합니다.-1items배열에2이(가) 없는 경우 인덱스에 [-1]을(를) 반환합니다.nullitems이 배열이 아니거나items가 존재하지 않는 경우에 대한 인덱스.
출력 예시:
[ { _id: 0, index: -1 }, { _id: 1, index: 1 }, { _id: 2, index: 1 }, { _id: 3, index: 2 }, { _id: 4, index: 0 }, { _id: 5, index: null }, { _id: 6, index: null } ]