MongoDB Aggregation join array of strings to single string

前端 未结 4 865
长发绾君心
长发绾君心 2021-02-12 15:14

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

Given is the following dataset:

Collection 1:

{
  id: 123         


        
4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 15:26

    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.

提交回复
热议问题