Docs 主页 → 开发应用程序 → MongoDB Manual
$indexOfArray(聚合)
定义
$indexOfArray
版本 3.4 中的新增功能。
在数组中搜索指定值的出现位置,并返回第一次出现该值的数组索引(从零开始)。 如果未找到该值,则返回
-1
。{ $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>
为空值,或者如果
<array expression>
引用输入文档中不存在的字段。
$indexOfArray
返回错误:
如果
<array expression>
不是数组且不为空值,或者如果
<start>
或<end>
是负整数(或可以表示为负整数的值,例如 -5.0)。
$indexOfArray
返回-1
:
如果在数组中未找到 <搜索表达式>,或是
如果
<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" ] } | 错误 |
例子
该示例使用此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 } ]