On this page本页内容
$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.有关表达式的详细信息,请参阅表达式。
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字符字符串具有定义良好的行为。
Consider an 考虑使用以下文档进行库存集合:inventory
collection with the following documents:
{ "_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
运算符将quarter
值分隔为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" }