$substr (aggregation)
On this page本页内容
Definition定义
$substr
Deprecated since version 3.4:自3.4版以来已弃用:$substr
is now an alias for$substrBytes
.$substr
现在是$substrBytes
的别名。Returns a substring of a string, starting at a specified index position and including the specified number of characters. The index is zero-based.返回字符串的子字符串,从指定的索引位置开始,包含指定数量的字符。该索引以零为基础。$substr
has the following syntax:具有以下语法:{ $substr: [ <string>, <start>, <length> ] }
The arguments can be any valid expression as long as the first argument resolves to a string, and the second and third arguments resolve to integers.只要第一个参数解析为字符串,第二个和第三个参数解析成整数,参数就可以是任何有效的表达式。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
Behavior行为
If 如果<start>
is a negative number, $substr
returns an empty string ""
.<start>
是负数,$substr
将返回一个空字符串""
。
If 如果<length>
is a negative number, $substr
returns a substring that starts at the specified index and includes the rest of the string.<length>
是负数,$substr
将返回一个从指定索引开始并包含字符串其余部分的子字符串。
$substr
only has a well-defined behavior for strings of ASCII characters.仅对ASCII字符字符串具有定义良好的行为。
Example实例
Consider an 考虑一个包含以下文档的inventory
collection with the following documents:inventory
集合:
{ "_id" : 1, "item" : "ABC1", quarter: "13Q1", "description" : "product 1" }
{ "_id" : 2, "item" : "ABC2", quarter: "13Q4", "description" : "product 2" }
{ "_id" : 3, "item" : "XYZ1", quarter: "14Q2", "description" : null }
The following operation uses the 以下操作使用$substr
operator to separate the quarter
value into a yearSubstring
and a quarterSubstring
:$substr
运算符将季度值分隔为yearSubstring
和quarterSubstring
:
db.inventory.aggregate(
[
{
$project:
{
item: 1,
yearSubstring: { $substr: [ "$quarter", 0, 2 ] },
quarterSubtring: { $substr: [ "$quarter", 2, -1 ] }
}
}
]
)
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "item" : "ABC1", "yearSubstring" : "13", "quarterSubtring" : "Q1" }
{ "_id" : 2, "item" : "ABC2", "yearSubstring" : "13", "quarterSubtring" : "Q4" }
{ "_id" : 3, "item" : "XYZ1", "yearSubstring" : "14", "quarterSubtring" : "Q2" }