3

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.

1 Answer 1

3

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'
  }}
])
Sign up to request clarification or add additional context in comments.

4 Comments

Instead of plus sign use ,
Yes, all field show up correctly but the new field "fullName" is null.
try with { '$addFields': { 'fullName' : { '$concat': ['$$employee.name', ' ', '$$employee.surname'] }}}
@matthPen No man!!! $ is used for the document fields and $$ is used for the variables

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.