On this page本页内容
$indexOfArray
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:具有以下运算符表达式语法:
{ $indexOfArray: [ <array expression>, <search expression>, <start>, <end> ] }
<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
集合:
{ "_id" : 1, "items" : ["one", "two", "three"] } { "_id" : 2, "items" : [1, 2, 3] } { "_id" : 3, "items" : [null, null, 2] } { "_id" : 4, "items" : null } { "_id" : 5, "amount" : 3 }
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
数组中的数组索引:
db.inventory.aggregate( [ { $project: { index: { $indexOfArray: [ "$items", 2 ] }, } } ] )
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "index" : "-1" } { "_id" : 2, "index" : "1" } { "_id" : 3, "index" : "2" } { "_id" : 4, "index" : null } { "_id" : 5, "index" : null }