$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
returnsnull
.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 }