$indexOfArray (聚合)
定义
$indexOfArray
在数组中搜索指定值的首次出现,并返回该值的数组索引。数组索引从零开始。
{ $indexOfArray: [ <array expression>, <search expression>, <start>, <end> ] } 字段类型描述<array>
数组可以是任何有效的表达式,只要它解析为数组。有关表达式的更多信息,请参阅表达式运算符。
如果数组表达式解析为
null
或引用一个缺失的字段,$indexOfArray
返回null
。如果数组表达式不解析为数组或
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>
为null,或者如果
<array expression>
引用输入文档中不存在的字段。
$indexOfArray
返回错误
如果
<array expression>
不是数组且不为null,或者如果
<start>
或<end>
是负整数(或可以表示为负整数的值,如-5.0)。
$indexOfArray
返回-1
如果数组中未找到
<search expression>
,或者如果
<start>
是一个大于<end>
的数字,或者如果
<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" ] } | 错误 |
示例
示例使用此 库存
集合
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
开始。如果
2
不在items
数组中,则索引为-1
。如果
items
不是数组或items
不存在,则索引为null
。
示例输出
[ { _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 } ]