MongoDB $concat Operator Examples
In the following examples, we are working with:
Database: w3wiki
Collection: employee
Document: three documents that contain the details of the employees in the form of field-value pairs.
Example 1: Concatenating strings using $concat operator
In this example, we are finding the department of the employees. Here, we concatenate “My department is:” string with the value of the department field.
Query:
db.employee.aggregate([
... {$project: {"name.first": 1, _id: 0, dept:
... {$concat: ["My department is: ", "$department"]}}}])
Output:
Example 2: Concatenating strings in the embedded documents using $concat operator
In this example, we are going to find the full name of the employees by concatenating the values of the name.first, name.middle, and name.last fields.
Query:
db.employee.aggregate([
... {$project: {fullname:
... {$concat: ["$name.first", "$name.middle", "$name.last"]}}}])
Output:
MongoDB – $concat Operator
MongoDB $concat or concatenation operator concatenates two or more strings and returns a single string. The $concat operator is one of the string expression operators that is used in the aggregation pipeline stages.