Database Manual / Reference / Query Language / Expressions

$substr (expression operator)(表达式运算符)

Definition定义

$substr

Deprecated since version 3.4: 自3.4版本起已弃用:$substr is now an alias for $substrBytes.$strr现在是$strBytes的别名。

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>是一个负数,$subr将返回一个空字符串""

If <length> is a negative number, $substr returns a substring that starts at the specified index and includes the rest of the string.如果<length>是负数,$subr将返回一个子字符串,该子字符串从指定的索引开始,并包括字符串的其余部分。

$substr only has a well-defined behavior for strings of ASCII characters.仅对ASCII字符串具有明确定义的行为。

Example示例

Consider an inventory collection with the following documents:考虑使用以下文件进行inventory集合:

db.inventory.insertMany( [
{ _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(季度)值分为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" }