MongoDB $concat

In MongoDB, the $concat aggregation pipeline operator concatenates two or more strings and returns the concatenated string.

Example

Suppose we have a collection called employees with the following document:

{
	"_id" : 1,
	"firstName" : "Sandy",
	"surname" : "Beach",
	"position" : "Lifesaver",
	"salary" : 55000
}

We can use the $concat operator to concatenate the first name and surname:

db.employees.aggregate(
  [
    { $project: { 
        _id: 0,
        name: { $concat: [ "$firstName", "$surname" ] }
      }
    }
  ]
)

Result:

{ "name" : "SandyBeach" }

More Strings

The previous example concatenates two strings, but we can concatenate more if required.

For example, we could insert a space between the first name and the surname.

Example:

db.employees.aggregate(
  [
    { $project: { 
        _id: 0,
        name: { $concat: [ "$firstName", " ", "$surname" ] }
      }
    }
  ]
)

Result:

{ "name" : "Sandy Beach" }

We can also include more fields in our concatenation.

Example:

db.employees.aggregate(
  [
    { $project: { 
        _id: 0,
        employee: { 
          $concat: [ "$firstName", " ", "$surname", ", ", "$position" ] 
          }
      }
    }
  ]
)

Result:

{ "employee" : "Sandy Beach, Lifesaver" }

Other Data Types

The $concat operator only supports strings. Applying $concat to a different type results in an error.

Example:

db.employees.aggregate(
  [
    { $project: { 
        _id: 0,
        name: { 
          $concat: [ "$firstName", "$salary" ] 
          }
      }
    }
  ]
)

Result:

Error: command failed: {
	"ok" : 0,
	"errmsg" : "$concat only supports strings, not double",
	"code" : 16702,
	"codeName" : "Location16702"
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:618:17
assert.commandWorked@src/mongo/shell/assert.js:708:16
DB.prototype._runAggregate@src/mongo/shell/db.js:266:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1046:12
@(shell):1:1

In this example I tried to concatenate a string with a number but I got an error that states $concat only supports strings, not double.