Skip to content
Related Articles

Related Articles

MongoDB $concat Operator
  • Last Updated : 01 Aug, 2020

MongoDB provides different types of string expression operators that are used in the aggregation pipeline stages $concat operator is one of them. This operator is used to concatenate two or more strings and returns a single string.

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.

Examples:

In the following examples, we are working with:



Database: GeeksforGeeks

Collection: employee

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

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.

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

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. 

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :