定义
$indexOfBytes在字符串中搜索子string的出现位置,并返回第一次出现时的 UTF-8 字节索引(从零开始)。 如果未找到子字符串,则返回
-1。$indexOfByteshas the following operator expression syntax:{ $indexOfBytes: [ <string expression>, <substring expression>, <start>, <end> ] } 操作数说明<string expression>可以是任何有效的表达式,只要它解析为字符串即可。 有关表达式的更多信息,请参阅表达式。
If the string expression resolves to a value of
nullor refers to a field that is missing,$indexOfBytesreturnsnull.If the string expression does not resolve to a string or
nullnor refers to a missing field,$indexOfBytesreturns an error.<substring expression><start>可选一个整数,用于指定Atlas Search的起始索引位置。 可以是解析为非负整数的任何有效表达式。
<end>Optional An integral number that specifies the ending index position for the search. Can be any valid expression that resolves to a non-negative integral number. If you specify a
<end>index value, you should also specify a<start>index value; otherwise,$indexOfBytesuses the<end>value as the<start>index value instead of the<end>value.
行为
If
<string expression>is null,$indexOfBytesreturnsnull.If
$indexOfBytesis called on a field that doesn't exist in the document,$indexOfBytesreturnsnull.If
<string expression>is not a string and not null,$indexOfBytesreturns an error.If
<substring expression>is null,$indexOfBytesreturns an error.If
<start>or<end>is a negative number,$indexOfBytesreturns an error.If
<start>is a number greater than<end>,$indexOfBytesreturns-1.If
<start>is a number greater than the byte length of the string,$indexOfBytesreturns-1.If
<start>or<end>is given a value that is not an integer,$indexOfBytesreturns an error.If the
<substring expression>is found multiple times within the<string expression>, then$indexOfBytesreturns the index of the first<substring expression>found.
一些突出不同行为的简短示例:
例子 | 结果 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
示例
考虑包含以下文档的 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 $indexOfBytes operator to retrieve the indexes at which the string foo is located in each item:
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 }