拼接字符串操做,返回拼接后的字符串。语法格式以下:javascript
{ $concat: [ <expression1>, <expression2>, ... ] }
参数能够是任何有效的表达式,只要它们解析为字符串便可。 有关表达式的更多信息,请参阅 表达式。
准备如下测试数据:html
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字段,字段之间以 “-” 分割:java
db.inventory.aggregate( [ { $project: { itemDescription: { $concat: [ "$item", " - ", "$description" ] } } } ] )
运行结果以下:mongodb
{ "_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}
则查询时会抛错误,错误信息以下:express
{ "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