MongoDB Aggregation join array of strings to single string
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
.