MongoDB 字段拼接 $concat(aggregation)
生活随笔
收集整理的這篇文章主要介紹了
MongoDB 字段拼接 $concat(aggregation)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
$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
總結
以上是生活随笔為你收集整理的MongoDB 字段拼接 $concat(aggregation)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 地下城与勇士幸运星租用武器在什么地方
- 下一篇: 海信VIDAA MAX激光影院如何,在商