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.
Syntax
{ $concat: [ <expression1>, <expression2>, ... ] }
Here, the arguments passed in this operator can be any valid expression until they resolve to strings.
- If the entered argument resolves to null, then this operator will return null.
- If the entered argument refers to a missing field, then this operator will return null.
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:
Key Takeaways About $concat Operator
- The $concat operator in MongoDB is used to concatenate two or more strings into a single string.
- It is a powerful tool for string manipulation in MongoDB.
- It can be used with the $project stage of the aggregation pipeline to add a new field to the documents with the concatenated string.
- The $concat operator can be used with other aggregation operators, such as $trim, to further manipulate the strings.
Contact Us