$indexOfBytes (aggregation)

在本页面

Definition

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

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

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


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

Behavior

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

Example Results
{ $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 }
首页