當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


MongoDB $concat用法及代碼示例

MongoDB 提供了不同類型的 s字符串表達式運算符用於聚合管道階段$連接 操作符就是其中之一。這操作員習慣於連接兩個或多個字符串和返回單個字符串。

用法:

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

在這裏,在這個運算符中傳遞的參數可以是任何有效的表達式,直到它們解析為字符串。

  • 如果輸入的參數解析為 null,則此運算符將返回 null。
  • 如果輸入的參數表示了缺失的字段,則此運算符將返回 null。

例子:

在以下示例中,我們正在使用:



Database: GeeksforGeeks

Collection:employee

Document: three documents that contain the details of the employees in the form of field-value pairs.

連接字符串使用$concat 運算符:

在這個例子中,我們正在查找部門雇員。在這裏,我們將“我的部門是:”字符串與部門字段的值連接起來。

db.employee.aggregate([
... {$project:{"name.first":1, _id:0, dept:
... {$concat:["My department is:", "$department"]}}}])

連接嵌入文檔中的字符串使用$concat 運算符:

在這個例子中,我們將通過以下方式找到員工的全名連接 name.first、name.middle 和 name.last 字段的值。

db.employee.aggregate([
... {$project:{fullname:
... {$concat:["$name.first", "$name.middle", "$name.last"]}}}])

相關用法


注:本文由純淨天空篩選整理自ankita_saini大神的英文原創作品 MongoDB $concat Operator。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。