Definition定义
$concatConcatenates strings and returns the concatenated string.连接字符串并返回连接后的字符串。$concathas this 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
nullor refers to a field that is missing,$concatreturnsnull.
Example示例
Create an 使用以下文档创建inventory collection with these 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 }
] )
Use 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" ] } } }
]
)
Output:输出:
{ _id : 1, itemDescription : "ABC1 - product 1" }
{ _id : 2, itemDescription : "ABC2 - product 2" }
{ _id : 3, itemDescription : null }