On this page本页内容
$indexOfCP
Searches a string for an occurrence of a substring and returns the UTF-8 code point index (zero-based) of the first occurrence. 在字符串中搜索子字符串的匹配项,并返回第一个匹配项的UTF-8码位索引(从零开始)。If the substring is not found, returns 如果未找到子字符串,则返回-1
.-1
。
$indexOfCP
has the following operator expression syntax:具有以下运算符表达式语法:
{ $indexOfCP: [ <string expression>, <substring expression>, <start>, <end> ] }
<string> | string |
|
<substring> | string | |
<start> | integer |
|
<end> | integer |
|
If the 如果在<substring expression>
is found multiple times within the <string expression>
, then $indexOfCP
returns the index of the first <substring expression>
found from the starting index position.<string expression>
中多次找到<substring expression>
,则$indexOfCP
将返回从起始索引位置找到的第一个<substring expression>
的索引。
$indexOfCP
returns null
:
<string expression>
is null, or<string expression>
为空,或<string expression>
refers to a non-existing field in the input document.<string expression>
引用输入文档中不存在的字段。$indexOfCP
returns an error:返回错误:
<string expression>
is not a string and not null, or<string expression>
不是字符串且不为空,或者<substring expression>
is null or is not a string or refers to a nonexistent field in the input document, or<substring expression>
为空或不是字符串或引用输入文档中不存在的字段,或者<start>
or <end>
is a negative integer (or a value that can be represented as a negative integer, like -5.0).<start>
或<end>
是负整数(或可以表示为负整数的值,如-5.0)。$indexOfCP
returns 返回-1
:-1
:
<string expression>
, or<string expression>
中找不到子字符串,或<start>
is a number greater than <end>
, or<start>
是大于<end>
的数字,或<start>
is a number greater than the byte length of the string.<start>
是一个大于字符串字节长度的数字。{ $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 |
Consider an 考虑使用以下文档进行inventory
collection with the following documents: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 }
The following operation uses the 以下操作使用$indexOfCP
operator to return the code point index at which the string foo
is located in each item
string:$indexOfCP
运算符返回每个项目字符串中字符串foo
所在的代码点索引:
db.inventory.aggregate( [ { $project: { cpLocation: { $indexOfCP: [ "$item", "foo" ] }, } } ] )
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "cpLocation" : "0" } { "_id" : 2, "cpLocation" : "3" } { "_id" : 3, "cpLocation" : "4" } { "_id" : 4, "cpLocation" : "-1" } { "_id" : 5, "cpLocation" : null } { "_id" : 6, "cpLocation" : null }