Massimo Lavermicocca
Massimo Lavermicocca

Reputation: 175

$concat two fields in mongodb

I have this two collections:

employees :  {_id: NumberInt(0), name:"Max",surname:"Power"}, ..

and

loggableUser:{_id: NumberInt(0), employee: NumberInt(1), ..},

Now I have to insert into the following query a field "fullName" containing "employee.name" + " " + "employee.surname". I tried this query:

db.loggableUser.aggregate([
    {
      '$lookup':
      {
        'from': 'employees',
        'localField': 'employee',
        'foreignField' : '_id',
        'as': 'employee'
      }
    },
    { "$addFields":{ 
         "$employee.fullName" : "$employee.name" + " " + "$employee.surname"}])

but it does not work. I know is a simple thing but I can't get it works. Thank you.

Upvotes: 3

Views: 14050

Answers (1)

Ashh
Ashh

Reputation: 46491

You need to first $unwind the employee then you can use $concat to combine two fields.

db.loggableUser.aggregate([
  { '$lookup': {
    'from': 'employees',
    'localField': 'employee',
    'foreignField' : '_id',
    'as': 'employee'
  }},
  { '$unwind': '$employee' },
  { '$addFields': { 
    'employee.fullName' : { '$concat': ['$employee.name', ' ', '$employee.surname'] }
  }}
])

Which is far easier with the mongodb 3.6 and above $lookup syntax.

db.loggableUser.aggregate([
  { '$lookup': {
    'from': 'employees',
    'let': { 'employee': '$employee' },
    'pipeline': [
      { '$match': { '$expr': { '$eq': ['$_id', '$$employee'] }}},
      { '$addFields': { 'fullName' : { '$concat': ['$name', ' ', '$surname'] }}}
    ]
    'as': 'employee'
  }}
])

Upvotes: 3

Related Questions