$concat (aggregation)

Definition

  • $concat
  • Concatenates strings and returns the concatenated string.

$concat has the following syntax:

  1. { $concat: [ <expression1>, <expression2>, ... ] }

The arguments can be any valid expression as long as they resolve tostrings. For more information on expressions, seeExpressions.

If the argument resolves to a value of null or refers to a fieldthat is missing, $concat returns null.

Examples

Consider a inventory collection with the following documents:

  1. { "_id" : 1, "item" : "ABC1", quarter: "13Q1", "description" : "product 1" }
  2. { "_id" : 2, "item" : "ABC2", quarter: "13Q4", "description" : "product 2" }
  3. { "_id" : 3, "item" : "XYZ1", quarter: "14Q2", "description" : null }

The following operation uses the $concat operator toconcatenate the item field and the description field with a” - ” delimiter.

  1. db.inventory.aggregate(
  2. [
  3. { $project: { itemDescription: { $concat: [ "$item", " - ", "$description" ] } } }
  4. ]
  5. )

The operation returns the following results:

  1. { "_id" : 1, "itemDescription" : "ABC1 - product 1" }
  2. { "_id" : 2, "itemDescription" : "ABC2 - product 2" }
  3. { "_id" : 3, "itemDescription" : null }