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

$indexOfBytes(表达式操作符)

$indexOfBytes

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

$indexOfBytes 具有以下操作符表达式语法:

{ $indexOfBytes: [ <string expression>, <substring expression>, <start>, <end> ] }
操作数
说明

<string expression>

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

如果字符串表达式解析为 null 的值或引用了缺失的字段,$indexOfBytes 将返回 null。

如果字符串表达式未解析为字符串或 null,也未引用缺失字段,则 $indexOfBytes 将返回错误。

<substring expression>

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

<start>

可选一个整数,用于指定Atlas Search的起始索引位置。 可以是解析为非负整数的任何有效表达式。

<end>

可选 指定搜索结束索引位置的整数。可以是解析为非负整数的任何有效表达式。如果指定了 <end>索引值,则还应指定 <start>索引值;否则,$indexOfBytes 使用 <end> 值作为 <start>索引值,而不是 <end> 值。

  • 如果 <string expression> 为 null,则 $indexOfBytes 返回 null。

  • 如果对文档中不存在的字段调用 $indexOfBytes,则 $indexOfBytes 将返回 null。

  • 如果 <string expression> 不是字符串且不为 null,则 $indexOfBytes 将返回错误。

  • 如果 <substring expression> 为 null,则 $indexOfBytes 将返回错误。

  • 如果 <start> 或 <end> 为负数,则 $indexOfBytes 将返回错误。

  • 如果 <start> 是大于 <end> 的数字,$indexOfBytes 将返回 -1。

  • 如果 <start> 是大于字符串字节长度的数字,则 $indexOfBytes 返回 -1。

  • 如果为 <start> 或 <end> 提供的值不是整数,则 $indexOfBytes 将返回错误。

  • 如果在 <string expression> 中多次找到 <substring expression>,则 $indexOfBytes 返回找到的第一个 <substring expression> 的索引。

一些突出不同行为的简短示例:

例子
结果

{ $indexOfBytes: [ "cafeteria", "e" ] }

3

{ $indexOfBytes: [ "cafétéria", "é" ] }

3

{ $indexOfBytes: [ "cafétéria", "e" ] }

-1

{ $indexOfBytes: [ "cafétéria", "t" ] }

5

{ $indexOfBytes: [ "foo.bar.fi", ".", 5 ] }

7

{ $indexOfBytes: [ "vanilla", "ll", 0, 2 ] }

-1

{ $indexOfBytes: [ "vanilla", "ll", -1 ] }

-1

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

-1

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

-1

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

-1

{ $indexOfBytes: [ 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 }
] )

以下操作使用 $indexOfBytes操作符来检索字符串 foo 在每个项目中所在的索引:

db.inventory.aggregate(
[
{
$project:
{
byteLocation: { $indexOfBytes: [ "$item", "foo" ] },
}
}
]
)

操作返回以下结果:

{ _id: 1, byteLocation: "0" }
{ _id: 2, byteLocation: "4" }
{ _id: 3, byteLocation: "4" }
{ _id: 4, byteLocation: "-1" }
{ _id: 5, byteLocation: null }
{ _id: 6, byteLocation: null }
给本页内容打分

在此页面上