定义
$substr自版本 3.4 起已弃用:
$substris now an alias for$substrBytes.返回字符串的子字符串,从指定索引位置开始并包含指定数量的字符。该索引从零开始。
$substr通过以下语法实现:{ $substr: [ <string>, <start>, <length> ] } 只要第一个参数解析为字符串,并且第二个和第三个参数解析为整数,参数就可以是任何有效的表达式。 有关表达式的更多信息,请参阅表达式。
行为
If <start> is a negative number, $substr returns an empty string "".
If <length> is a negative number, $substr returns a substring that starts at the specified index and includes the rest of the string.
$substr 仅对 ASCII 字符字符串有明确定义的行为。
例子
以下示例使用 sample_mflix 示例数据集中的 movies 集合。有关如何将此数据集加载到部署中的详细信息,请参阅 加载示例数据集。
This aggregation operation uses the $substr operator to separate the title value into a titleStart and a titleRest. The second expression uses a negative <length> to return the characters from index 3 to the end of the string:
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $project: { _id: 0, title: 1, titleStart: { $substr: [ "$title", 0, 3 ] }, titleRest: { $substr: [ "$title", 3, -1 ] } } } ] )
[ { title: 'Centennial', titleStart: 'Cen', titleRest: 'tennial' }, { title: 'Baseball', titleStart: 'Bas', titleRest: 'eball' } ]