On this page本页内容
$indexOfArray¶New in version 3.4.版本3.4中的新功能。
Searches an array for an occurrence of a specified value and returns the array index (zero-based) of the first occurrence. 在数组中搜索指定值的匹配项,并返回第一个匹配项的数组索引(从零开始)。If the value is not found, returns 如果找不到该值,则返回-1.-1。
$indexOfArray has the following operator expression syntax:具有以下运算符表达式语法:
<array> |
string |
|
<search value> |
string | |
<start> |
integer |
|
<end> |
integer |
|
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.<array expression>中多次找到<search expression>,则$indexOfArray从起始索引位置返回第一个<search expression>的索引。
$indexOfArray returns 返回null:null
<array expression> is null, or<array expression>为null,或<array expression> refers to a non-existing field in the input document.<array expression>引用的是输入文档中不存在的字段。$indexOfArray returns an error:返回一个错误:
<array expression> is not an array and not null, or<array expression>不是数组且不为空,或<start> or <end> is a negative integer (or a value that can be represented as a negative integer, like -5.0).<start>或<end>是负整数(或可以表示为负整数的值,如-5.0)。$indexOfArray returns 返回-1:-1:
<search expression>,或<start> is a number greater than <end>, or<start>大于<end>,或<start> is a number greater than the length of the array.<start>是一个大于数组长度的数字。{ $indexOfArray: [ [ "a", "abc" ], "a" ] } |
0 |
{ $indexOfArray: [ [ "a", "abc", "de", ["de"] ], ["de"] ] } |
3 |
{ $indexOfArray: [ [ 1, 2 ], 5 ] } |
-1 |
{ $indexOfArray: [ [ 1, 2, 3 ], [1, 2] ] } |
-1 |
{ $indexOfArray: [ [ 10, 9, 9, 8, 9 ], 9, 3 ] } |
4 |
{ $indexOfArray: [ [ "a", "abc", "b" ], "b", 0, 1 ] } |
-1 |
{ $indexOfArray: [ [ "a", "abc", "b" ], "b", 1, 0 ] } |
-1 |
{ $indexOfArray: [ [ "a", "abc", "b" ], "b", 20 ] } |
-1 |
{ $indexOfArray: [ [ null, null, null ], null ] } |
0 |
{ $indexOfArray: [ null, "foo" ] } |
null |
{ $indexOfArray: [ "foo", "foo" ] } |
Error |
Consider an 考虑带有以下文档的inventory collection with the following documents:inventory集合:
The following operation uses the 以下操作使用$indexOfArray operator to return the array index at which the string foo is located in each items array:$indexOfArray运算符返回字符串foo在每个items数组中所处的数组索引:
The operation returns the following results:操作返回以下结果:
See also参阅
$indexOfBytes, $indexOfCP, and $in