$indexOfBytes (aggregation)

在本页面

Definition

  • $indexOfBytes
    • 3.4 版的新功能。

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

$indexOfBytes具有以下运算符表达式语法

{ $indexOfBytes: [ <string expression>, <substring expression>, <start>, <end> ] }
OperandDescription
<string expression>可以是任何有效的expression,只要它解析为字符串即可。有关表达式的更多信息,请参见Expressions


如果字符串表达式解析为null的值或引用了缺少的字段,则$indexOfBytes返回null
如果字符串表达式不能解析为字符串或null,也没有引用丢失的字段,则$indexOfBytes返回错误。
| <substring expression> |可以是任何有效的expression,只要它解析为字符串即可。有关表达式的更多信息,请参见Expressions
| <start> | 可选一个整数,指定搜索的起始索引位置。可以是解析为非负整数的任何有效expression
| <end> | 可选一个整数,指定搜索的结束索引位置。可以是解析为非负整数的任何有效expression。如果指定<end>索引值,则还应指定<start>索引值。否则,$indexOfBytes使用<end>值作为<start>索引值而不是<end>值。

Behavior

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

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

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

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

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

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

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

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

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

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

ExampleResults
{ $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

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 }

以下操作使用$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 }