- Reference >
- Operators >
- Aggregation Framework Operators >
- String Aggregation Operators >
- $concat (aggregation)
$concat (aggregation)¶
-
$concat¶ New in version 2.4.
Takes an array of strings, concatenates the strings, and returns the concatenated string.
$concatcan only accept an array of strings.Use
$concatwith the following syntax:If array element has a value of
nullor refers to a field that is missing,$concatwill returnnull.Example
Project new concatenated values.
A collection
menucontains the documents that stores information on menu items separately in thesection, thecategoryand thetypefields, as in the following:The following operation uses
$concatto concatenate thetypefield from the sub-documentitem, a space, and thecategoryfield from the sub-documentitemto project a newfoodfield:The operation returns the following result set where the
foodfield contains the concatenated strings:Example
Group by a concatenated string.
A collection
menucontains the documents that stores information on menu items separately in thesection, thecategoryand thetypefields, as in the following:The following aggregation uses
$concatto concatenate thesecfield from the sub-documentitem, the string": ", and thecategoryfield from the sub-documentitemto group by the new concatenated string and perform a count:The aggregation returns the following document:
Example
Concatenate
nullor missing values.A collection
menucontains the documents that stores information on menu items separately in thesection, thecategoryand thetypefields. Not all documents have the all three fields. For example, the document with_idequal to5is missing thecategoryfield:The following aggregation uses the
$concatto concatenate thetypefield from the sub-documentitem, a space, and thecategoryfield from the sub-documentitem:Because the document with
_idequal to5is missing thetypefield in theitemsub-document,$concatreturns the valuenullas the concatenated value for the document:To handle possible missing fields, you can use
$ifNullwith$concat, as in the following example which substitutes<unknown type>if the fieldtypeisnullor missing, and<unknown category>if the fieldcategoryisnullor is missing:The aggregation returns the following result set: