文档菜单
文档首页
/
MongoDB 手册
/ / /

$concat (聚合)

本页内容

  • 定义
  • 示例
$concat

将字符串连接并返回连接后的字符串。

$concat的语法如下

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

参数可以是任何有效的表达式,只要它们解析为字符串。有关表达式的更多信息,请参阅表达式运算符。

如果参数解析为null值或引用了一个缺失的字段,则$concat返回null

创建包含以下文档的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 }
] )

使用$concat运算符将item字段和description字段使用" - "分隔符连接

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

输出

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

返回

$cmp

本页内容