“文档” 菜单
文档首页
/
MongoDB Manual
/ / /

$concat(聚合)

在此页面上

  • 定义
  • 举例
$concat

连接多个字符串并返回连接后的字符串。

$concat 通过以下语法实现:

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

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

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

请考虑包含以下文档的 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 }

以下操作使用 $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(聚合)

在此页面上