$indexOfCP
聚合运算符使用UTF-8代码点搜索字符串中出现的子字符串第一次出现的位置(从零开始)。如果未找到子字符串,则返回 -1。
语法
{ $indexOfCP: [ <string expression>, <substring expression>, <start>, <end> ] }
$indexOfCP
参数说明:
字段 | 类型 | 是否必须 | 说明 |
---|---|---|---|
<string> | 字符串 | 是 | 能够解析为字符串的表达式,如果表达式的值为null或引用的字段缺失,$indexOfCP 返回null ;如果表达式结果为非字符串或null 且引用字段都存在,$indexOfCP 返回错误 |
<substring> | 字符串 | 是 | 能够解析为字符串的表达式 |
<start> | 整数 | 否 | 大于等于零的整数或能转换为整数的数值(如:2.0)表达式,如果不指定则从开始搜索 |
<end> | 整数 | 否 | 大于等于零的整数或能转换为整数的数值(如:2.0)表达式。如果指定的<end> 则应该也要指定<start> 否则<end> 就会被当做<start> ,如果不指定则搜索到最后 |
使用
- 如果
<substring string>
在<string expression>
中出现多次,返回第一次出现的位置。 - 下面的情况
$indexOfCP
返回null
:<string expression>
为null
<string expression
引用的字段不存在
- 下面的情况
$indexOfCP
返回错误:<string expresion>
不为空且值不是字符串<substring expression>
为空或不是字符串或引用不存在的字段<start>
或<end>
为负数
- 下面的情况
$indexOfCP
返回-1
:- 在
<string expression>
中不包含<substring expression>
<start>
大于<end>
<start>
大于字符串的字节长度
- 在
下面是一些例子来说明典型的规则:
举例 | 结果 |
---|---|
{ $indexOfCP: [ "cafeteria", "e" ] } | 3 |
{ $indexOfCP: [ "cafétéria", "é" ] } | 3 |
{ $indexOfCP: [ "cafétéria", "e" ] } | -1 |
{ $indexOfCP: [ "cafétéria", "t" ] } | 4 |
{ $indexOfCP: [ "foo.bar.fi", ".", 5 ] } | 7 |
{ $indexOfCP: [ "vanilla", "ll", 0, 2 ] } | -1 |
{ $indexOfCP: [ "vanilla", "ll", -1 ] } | Error |
{ $indexOfCP: [ "vanilla", "ll", 12 ] } | -1 |
{ $indexOfCP: [ "vanilla", "ll", 5, 2 ] } | -1 |
{ $indexOfCP: [ "vanilla", "nilla", 3 ] } | -1 |
{ $indexOfCP: [ null, "foo" ] } | null |
举例
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 }
下面的聚合操作使用indexOfCP
运算符来检索字符串foo
在每个item中的编码点位置:
db.inventory.aggregate(
[
{
$project:
{
cpLocation: { $indexOfCP: [ "$item", "foo" ] },
}
}
]
)
操作的结果如下:
{ "_id" : 1, "cpLocation" : "0" }
{ "_id" : 2, "cpLocation" : "3" }
{ "_id" : 3, "cpLocation" : "4" }
{ "_id" : 4, "cpLocation" : "-1" }
{ "_id" : 5, "cpLocation" : null }
{ "_id" : 6, "cpLocation" : null }