定义
$indexOfCP在字符串中搜索子字符串的出现位置,并返回第一次出现时的 UTF-8 码点索引(从零开始)。如果未找到子字符串,则返回
-1。$indexOfCPhas the following operator expression syntax:{ $indexOfCP: [ <string expression>, <substring expression>, <start>, <end> ] } 字段类型说明<string>字符串
可以是任何有效的表达式,只要它解析为字符串即可。 有关表达式的更多信息,请参阅表达式。
If the string expression resolves to a value of
nullor refers to a field that is missing,$indexOfCPreturnsnull.If the string expression does not resolve to a string or
nullnor refers to a missing field,$indexOfCPreturns an error.<substring>字符串
<start>整型
可选。一个整数或可以表示为整数的数字(例如 2.0),用于指定搜索的起始索引位置。可以是任何能够解析为非负整数的有效表达式。
如果未指定,则搜索的起始索引位置为字符串的开头。
<end>整型
可选。一个整数或可以表示为整数的数字(例如2.0 ),用于指定搜索的结束索引位置。可以是解析为非负整数的任何有效表达式。如果指定
<end>索引值,则还应指定<start>索引值;否则,$indexOfCP会使用<end>值作为<start>索引值,而不是<end>值。如果未指定,则搜索的结束索引位置为字符串的末尾。
行为
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.
$indexOfCP returns null:
如果
<string expression>为空值,或者如果
<string expression>引用输入文档中不存在的字段。
$indexOfCP 返回错误:
如果
<string expression>不是字符串且不为 null,或者如果
<substring expression>为 null 或不是字符串或引用输入文档中不存在的字段,或者如果
<start>或<end>是负整数(或可以表示为负整数的值,例如 -5.0)。
$indexOfCP returns -1:
如果在
<string expression>或如果
<start>为大于<end>的数字,或是如果
<start>是一个大于字符串字节长度的数字。
例子 | 结果 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
| 错误 |
|
|
|
|
|
|
|
|
示例
考虑包含以下文档的 inventory 集合:
db.inventory.insertMany( [ { _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:
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 }