$indexOfBytes(聚合)
定义
$indexOfBytes
在字符串中搜索子string的出现位置,并返回第一次出现时的 UTF-8 字节索引(从零开始)。 如果未找到子字符串,则返回
-1
。{ $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>
不是string且不为空值,$indexOfBytes
将返回错误。如果
<substring expression>
为 null,则$indexOfBytes
将返回错误。如果
<start>
或<end>
为负数,$indexOfBytes
将返回错误。如果
<start>
是大于<end>
的数字,则$indexOfBytes
返回-1
。如果
<start>
是大于string字节长度的数字,则$indexOfBytes
返回-1
。如果
<start>
或<end>
赋予的值不是整数,则$indexOfBytes
将返回错误。如果在
<string expression>
中多次找到<substring expression>
,则$indexOfBytes
返回找到的第一个<substring expression>
的索引。
一些突出不同行为的简短示例:
例子 | 结果 |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
示例
考虑包含以下文档的 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
操作符来检索string 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 }
另请参阅: