Search code examples
mongodbaggregation-frameworkstring-concatenation

MongoDB Aggregation join array of strings to single string


We're trying to 'join' an array of strings to a single string within an aggregation.

Given is the following dataset:

Collection 1:

{
  id: 1234,
  field: 'test'
}

Collection 2:

{
  id: 1111,
  collection1_id: 1234,
  name: 'Max'
},
{
  id: 1112,
  collection1_id: 1234,
  name: 'Andy'
}

The current result (after lookup etc.):

{
  id: 1234,
  field: 'test',
  collection2: ['Max', 'Andy'] 
}

The desired result:

{
  id: 1234,
  field: 'test',
  collection2: 'Max, Andy'
}

Is it somehow possible to join the 'collection2' to a single string? We've tried with $concat but it only accepts strings.


Solution

  • You were on the right track.

    Just add $reduce over $concat in your $project stage.

    'collection2': {
        '$reduce': {
            'input': '$collection2',
            'initialValue': '',
            'in': {
                '$concat': [
                    '$$value',
                    {'$cond': [{'$eq': ['$$value', '']}, '', ', ']}, 
                    '$$this']
            }
        }
    }
    

    Note: We use $cond to prevent a leading , in the concatenation. You could also use $substrCP before $reduce as an alternative to $cond.