MongoDB $concat Operator

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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.