$concat (aggregation)

On this page本页内容

Definition定义

$concat

Concatenates strings and returns the concatenated string.连接字符串并返回连接的字符串。

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

{ $concat: [ <expression1>, <expression2>, ... ] }

The arguments can be any valid expression as long as they resolve to strings. 参数可以是任何有效的表达式,只要它们解析为字符串。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

If the argument resolves to a value of null or refers to a field that is missing, $concat returns null.如果参数解析为null值或引用缺少的字段,$concat返回null

Examples示例

Consider a 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 $concat operator to concatenate the item field and the description field with a ” - ” delimiter.下面的操作使用$concat运算符将item字段和description字段用“-”分隔符连接起来。

db.inventory.aggregate(
   [
      { $project: { itemDescription: { $concat: [ "$item", " - ", "$description" ] } } }
   ]
)

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

{ "_id" : 1, "itemDescription" : "ABC1 - product 1" }
{ "_id" : 2, "itemDescription" : "ABC2 - product 2" }
{ "_id" : 3, "itemDescription" : null }