On this page
$indexOfCP (aggregation)
在本页面
Definition
$indexOfCP
- 3.4 版的新功能。
在字符串中搜索子字符串的出现,并返回第一次出现的 UTF-8 code point索引(从零开始)。如果未找到子字符串,则返回-1
。
$indexOfCP具有以下运算符表达式语法:
{ $indexOfCP: [ <string expression>, <substring expression>, <start>, <end> ] }
Field | Type | Description |
---|---|---|
<string> |
string | 可以是任何有效的expression,只要它解析为字符串即可。有关表达式的更多信息,请参见Expressions。 |
如果字符串表达式解析为null
的值或引用了缺少的字段,则$indexOfCP返回null
。
如果字符串表达式不能解析为字符串或null
,也没有引用丢失的字段,则$indexOfCP返回错误。
| <substring>
| string |可以是任何有效的expression,只要它解析为字符串即可。有关表达式的更多信息,请参见Expressions。
| <start>
|整数|可选。一个整数或可以表示为整数的数字(例如 2.0),它指定搜索的起始索引位置。可以是解析为非负整数的任何有效expression。
如果未指定,则搜索的起始索引位置为字符串的开头。
| <end>
|整数|可选。一个整数或可以表示为整数的数字(例如 2.0),它指定搜索的结束索引位置。可以是解析为非负整数的任何有效expression。如果指定<end>
索引值,则还应指定<start>
索引值。否则,$indexOfCP会将<end>
值用作<start>
索引值而不是<end>
值。
如果未指定,则搜索的结束索引位置为字符串的结尾。
Behavior
如果在<string expression>
内多次找到<substring expression>
,则$indexOfCP返回从起始索引位置找到的第一个<substring expression>
的索引。
$indexOfCP返回null
:
如果
<string expression>
为空,或者如果
<string expression>
引用 Importing 文档中不存在的字段。
$indexOfCP返回错误:
如果
<string expression>
不是字符串也不是 null,或者如果
<substring expression>
为 null 或不是字符串,或者引用 Importing 文档中不存在的字段,或者如果
<start>
或<end>
是负整数(或可以表示为负整数的值,例如-5.0)。
$indexOfCP返回-1
:
如果在
<string expression>
中找不到子字符串,或者如果
<start>
是大于<end>
的数字,或者如果
<start>
是大于字符串字节长度的数字。
Example | Results |
---|---|
{ $indexOfCP: [ "cafeteria", "e" ] } |
3 |
{ $indexOfCP: [ "cafétéria", "é" ] } |
3 |
{ $indexOfCP: [ "cafétéria", "e" ] } |
-1 |
{ $indexOfCP: [ "cafétéria", "t" ] } |
4 |
{ $indexOfCP: [ "foo.bar.fi", ".", 5 ] } |
7 |
{ $indexOfCP: [ "vanilla", "ll", 0, 2 ] } |
-1 |
{ $indexOfCP: [ "vanilla", "ll", -1 ] } |
Error |
{ $indexOfCP: [ "vanilla", "ll", 12 ] } |
-1 |
{ $indexOfCP: [ "vanilla", "ll", 5, 2 ] } |
-1 |
{ $indexOfCP: [ "vanilla", "nilla", 3 ] } |
-1 |
{ $indexOfCP: [ null, "foo" ] } |
null |
Examples
考虑包含以下文档的inventory
集合:
{ "_id" : 1, "item" : "foo" }
{ "_id" : 2, "item" : "fóofoo" }
{ "_id" : 3, "item" : "the foo bar" }
{ "_id" : 4, "item" : "hello world fóo" }
{ "_id" : 5, "item" : null }
{ "_id" : 6, "amount" : 3 }
以下操作使用$indexOfCP运算符返回每个item
字符串中的字符串foo
所在的代码点索引:
db.inventory.aggregate(
[
{
$project:
{
cpLocation: { $indexOfCP: [ "$item", "foo" ] },
}
}
]
)
该操作返回以下结果:
{ "_id" : 1, "cpLocation" : "0" }
{ "_id" : 2, "cpLocation" : "3" }
{ "_id" : 3, "cpLocation" : "4" }
{ "_id" : 4, "cpLocation" : "-1" }
{ "_id" : 5, "cpLocation" : null }
{ "_id" : 6, "cpLocation" : null }
See also