Docs HomeMongoDB Manual

$substr (aggregation)

On this page本页内容

Definition定义

$substr

Deprecated since version 3.4: $substr is now an alias for $substrBytes.自3.4版以来已弃用$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运算符将季度值分隔为yearSubstringquarterSubstring

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" }