$trim (aggregation)

On this page本页内容

Definition定义

$trim

New in version 4.0.版本4.0中的新功能。

Removes whitespace characters, including null, or the specified characters from the beginning and end of a string.

$trim has the following syntax:语法如下所示:

{ $trim: { input: <string>,  chars: <string> } }

The $trim takes a document with the following fields:

Field字段Description描述
input The string to trim. The argument can be any valid expression that resolves to a string. For more information on expressions, see Expressions.
chars

Optional.可选。The character(s) to trim from input.

The argument can be any valid expression that resolves to a string. The $trim operator breaks down the string into individual UTF code point to trim from input.

If unspecified, $trim removes whitespace characters, including the null character. For the list of whitespace characters, see Whitespace Characters.

See also参阅

$ltrim and $rtrim

Behavior行为

Whitespace Characters

By default, $trim removes the following whitespaces, including the null character:

UnicodeEscape sequenceDescription描述
U+0000 ‘0’ Null character
U+0020 ‘ ‘ Space
U+0009 ‘t’ Horizontal tab
U+000A ‘n’ Line feed/new line
U+000B ‘v’ Vertical tab
U+000C ‘f’ Form feed
U+000D ‘r’ Carriage return
U+00A0   Non-breaking space
U+1680   Ogham space mark
U+2000   En quad
U+2001   Em quad
U+2002   En space
U+2003   Em space
U+2004   Three-per-em space
U+2005   Four-per-em space
U+2006   Six-per-em space
U+2007   Figure space
U+2008   Punctuation space
U+2009   Thin space
U+200A   Hair space

Example示例

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 \n The product is in stock.  \n\n  " }
{ "_id" : 3, "item" : "XYZ1", quarter: "14Q2", "description" : null }

The following operation uses the $trim operator to remove leading and trailing whitespaces from the description field:

db.inventory.aggregate([
   { $project: { item: 1, description: { $trim: { input: "$description" } } } }
])

The operation returns the following results:操作返回以下结果:

{ "_id" : 1, "item" : "ABC1", "description" : "product 1" }
{ "_id" : 3, "item" : "XYZ1", "description" : null }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2 \n The product is in stock." }