- 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.
$concat
can only accept an array of strings.Use
$concat
with the following syntax:If array element has a value of
null
or refers to a field that is missing,$concat
will returnnull
.Example
Project new concatenated values.
A collection
menu
contains the documents that stores information on menu items separately in thesection
, thecategory
and thetype
fields, as in the following:The following operation uses
$concat
to concatenate thetype
field from the sub-documentitem
, a space, and thecategory
field from the sub-documentitem
to project a newfood
field:The operation returns the following result set where the
food
field contains the concatenated strings:Example
Group by a concatenated string.
A collection
menu
contains the documents that stores information on menu items separately in thesection
, thecategory
and thetype
fields, as in the following:The following aggregation uses
$concat
to concatenate thesec
field from the sub-documentitem
, the string": "
, and thecategory
field from the sub-documentitem
to group by the new concatenated string and perform a count:The aggregation returns the following document:
Example
Concatenate
null
or missing values.A collection
menu
contains the documents that stores information on menu items separately in thesection
, thecategory
and thetype
fields. Not all documents have the all three fields. For example, the document with_id
equal to5
is missing thecategory
field:The following aggregation uses the
$concat
to concatenate thetype
field from the sub-documentitem
, a space, and thecategory
field from the sub-documentitem
:Because the document with
_id
equal to5
is missing thetype
field in theitem
sub-document,$concat
returns the valuenull
as the concatenated value for the document:To handle possible missing fields, you can use
$ifNull
with$concat
, as in the following example which substitutes<unknown type>
if the fieldtype
isnull
or missing, and<unknown category>
if the fieldcategory
isnull
or is missing:The aggregation returns the following result set: