zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

MongoDB 字段拼接 $concat(aggregation)

2023-02-26 09:50:48 时间

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

{ $concat: [ , , … ] }
参数可以是任何有效的表达式,只要它们解析为字符串即可。 有关表达式的更多信息,请参阅表达式。
示例
准备以下测试数据:

(福利推荐:阿里云、腾讯云、华为云服务器最新限时优惠活动,云服务器1核2G仅88元/年、2核4G仅698元/3年,点击这里立即抢购>>>

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" : , "code" : 16702, "codeName" : "Location16702", "name" : "MongoError"

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

MongoDB 字段拼接 $concat(aggregation)


本站部分内容转载自网络,版权属于原作者所有,如有异议请联系QQ153890879修改或删除,谢谢!
转载请注明原文链接:MongoDB 字段拼接 $concat(aggregation)

你还在原价购买阿里云、腾讯云、华为云、天翼云产品?那就亏大啦!现在申请成为四大品牌云厂商VIP用户,可以3折优惠价购买云服务器等云产品,并且可享四大云服务商产品终身VIP优惠价,还等什么?赶紧点击下面对应链接免费申请VIP客户吧:

1、点击这里立即申请成为腾讯云VIP客户

2、点击这里立即注册成为天翼云VIP客户

3、点击这里立即申请成为华为云VIP客户

4、点击这里立享阿里云产品终身VIP优惠价

喜欢 (0)
[[email protected]]
分享 (0)