On this page
$indexOfArray (aggregation)
在本页面
Definition
$indexOfArray
- 3.4 版的新功能。
在数组中搜索指定值的出现,并返回第一个出现的数组索引(从零开始)。如果找不到该值,则返回-1
。
{ $indexOfArray: [ <array expression>, <search expression>, <start>, <end> ] }
Field | Type | Description |
---|---|---|
<array> |
string | 可以是任何有效的expression,只要它解析为数组即可。有关表达式的更多信息,请参见Expressions。 |
如果数组表达式解析为null
的值或引用了缺少的字段,则$indexOfArray返回null
。
如果数组表达式不能解析为数组或null
,也没有引用丢失的字段,则$indexOfArray返回错误。
| <search value>
| string |可以是任何有效的expression。有关表达式的更多信息,请参见Expressions。
| <start>
|整数|可选。一个整数或可以表示为整数的数字(例如 2.0),它指定搜索的起始索引位置。可以是解析为非负整数的任何有效expression。
如果未指定,则搜索的起始索引位置为字符串的开头。
| <end>
|整数|可选。一个整数或可以表示为整数的数字(例如 2.0),它指定搜索的结束索引位置。可以是解析为非负整数的任何有效expression。如果指定<end>
索引值,则还应指定<start>
索引值。否则,$indexOfArray会将<end>
值用作<start>
索引值而不是<end>
值。
如果未指定,则搜索的结束索引位置为字符串的结尾。
Behavior
如果在<array expression>
内多次找到<search expression>
,则$indexOfArray从起始索引位置返回第一个<search expression>
的索引。
$indexOfArray返回null
:
如果
<array expression>
为空,或者如果
<array expression>
引用 Importing 文档中不存在的字段。
$indexOfArray返回错误:
如果
<array expression>
不是数组且不为 null,或者如果
<start>
或<end>
是负整数(或可以表示为负整数的值,例如-5.0)。
$indexOfArray返回-1
:
如果在数组中找不到\ ,或者
如果
<start>
是大于<end>
的数字,或者如果
<start>
是大于数组长度的数字。
Example | Results |
---|---|
{ $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 |
Examples
考虑包含以下文档的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 }
以下操作使用$indexOfArray运算符返回每个items
数组中字符串foo
所在的数组索引:
db.inventory.aggregate(
[
{
$project:
{
index: { $indexOfArray: [ "$items", 2 ] },
}
}
]
)
该操作返回以下结果:
{ "_id" : 1, "index" : "-1" }
{ "_id" : 2, "index" : "1" }
{ "_id" : 3, "index" : "2" }
{ "_id" : 4, "index" : null }
{ "_id" : 5, "index" : null }
See also