定义
$indexOfArray搜索数组中出现的指定值,并返回首次出现的数组索引。数组索引从零开始。
{ $indexOfArray: [ <array expression>, <search expression>, <start>, <end> ] } 字段类型说明<array>阵列
可以是任何有效的表达式,只要它能解析为数组即可。有关表达式的更多信息,请参阅表达式。
如果大量表达式解析为
null的值或引用了缺失的字段,则$indexOfArraynull会返回 。如果大量表达式未解析为大量或
null,也未引用缺失字段,则$indexOfArray将返回错误。<search value>字符串
<start>整型
可选。一个整数或可以表示为整数的数字(例如 2.0),用于指定搜索的起始索引位置。可以是任何能够解析为非负整数的有效表达式。
如果未指定,则搜索的起始索引位置为字符串的开头。
<end>整型
可选。 一个整数或可以表示为整数的数字(例如 2.0),用于指定搜索的结束索引位置。 可以是解析为非负整数的任何有效表达式。如果指定
<end>索引值,则还应指定<start>索引值;否则,$indexOfArray会使用<end>值作为<start>索引值,而不是<end>值。如果未指定,则搜索的结束索引位置为字符串的末尾。
行为
如果在 <array expression> 中多次找到 <search expression>,则 $indexOfArray 返回从起始索引位置开始的第一个 <search expression> 的索引。
$indexOfArray 返回 null:
如果
<array expression>为空值,或者如果
<array expression>引用输入文档中不存在的字段。
$indexOfArray 返回错误:
如果
<array expression>不是数组且不为空值,或者如果
<start>或<end>是负整数(或可以表示为负整数的值,例如 -5.0)。
$indexOfArray 返回 -1:
如果在数组中未找到 <搜索表达式>,或是
如果
<start>为大于<end>的数字,或是如果
<start>是一个大于数组长度的数字。
例子 | 结果 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 错误 |
例子
该示例使用此inventory集合:
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 } ] )
以下示例使用 $indexOfArray 在 items 数组中查找 2:
db.inventory.aggregate( [ { $project: { index: { $indexOfArray: [ "$items", 2 ] } } } ] )
该示例返回:
每个
items数组中2值对应的第一个数组索引(如果能找到)。数组索引会从0开始。-1(对于索引)(如果2不在items数组中)。null,适用于items不是数组或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 } ]