MongoDB 字段拼接 $concat(aggregation)

本文详细介绍了 MongoDB 中的 $concat 操作符,用于字符串拼接,并展示了如何使用 $concat 在字段间进行拼接,同时讨论了当遇到不能解析为字符串的数据时可能引发的错误。

$concat

拼接字符串操作,返回拼接后的字符串。语法格式如下:

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

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

示例

准备以下测试数据:

db.inventory.drop();
var rows = 
[
	{ "_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 },
	{ "_id" : 4, "item" : "CCCC", quarter: "4000"}
];
db.inventory.insert(rows);

使用 $conct 连接 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},
{ "_id" : 4, "itemDescription" : null}

如果数据库中有不能解析成字符串的异常数据,例如如下数据:

{ "_id" : 5, "item" : "CCCC", quarter: "4000", "description" : 4}

则查询时会抛错误,错误信息如下:

{
	"message" : "$concat only supports strings, not double",
	"ok" : 0,
	"code" : 16702,
	"codeName" : "Location16702",
	"name" : "MongoError"
}

总结

在使用 $concat 是做字符串拼接操作时,如果参数解析为null值或引用缺少的字段,则 $concat 返回null。

来自个人博客:学习园
原文地址: https://xuexiyuan.cn/article/detail/222.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

什码情况

你的鼓励就是我最大的动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值