对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

$indexOfCP(表达式操作符)

$indexOfCP

在字符串中搜索子字符串的出现位置,并返回第一次出现时的 UTF-8 码点索引(从零开始)。如果未找到子字符串,则返回-1

$indexOfCP has the following operator expression syntax:

{ $indexOfCP: [ <string expression>, <substring expression>, <start>, <end> ] }
字段
类型
说明

<string>

字符串

可以是任何有效的表达式,只要它解析为字符串即可。 有关表达式的更多信息,请参阅表达式。

If the string expression resolves to a value of null or refers to a field that is missing, $indexOfCP returns null.

If the string expression does not resolve to a string or null nor refers to a missing field, $indexOfCP returns 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>是一个大于字符串字节长度的数字。

例子
结果

{ $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 ] }

错误

{ $indexOfCP: [ "vanilla", "ll", 12 ] }

-1

{ $indexOfCP: [ "vanilla", "ll", 5, 2 ] }

-1

{ $indexOfCP: [ "vanilla", "nilla", 3 ] }

-1

{ $indexOfCP: [ null, "foo" ] }

null

考虑包含以下文档的 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 }
给本页内容打分

在此页面上