MongoDB Aggregation将字符串数组连接到单个字符串

问题描述:

我们试图将一个字符串数组“连接”到聚合中的单个字符串。MongoDB Aggregation将字符串数组连接到单个字符串

鉴于是以下数据集:

类别1:

{ 
    id: 1234, 
    field: 'test' 
} 

系列2:

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

当前结果(查找等后):

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

期望的结果:

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

是它在某种程度上可以加入“collection2”到一个字符串?我们已经尝试了$concat,但它只接受字符串。

+0

添加您到目前为止的代码 –

要扁平化该数组,您需要将流程转移到客户端。

mongo将在新版本中提供一些新的展平选项,但afaik它将是算术平面(平均,最小,最大....)。

你在正确的轨道上。

只需在$project阶段添加$reduce超过$concat

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

注意:我们在$cond防止串联的领先,。 您也可以在$reduce之前使用$substrCP作为$cond的替代选项。

希望这会有所帮助!

+0

给Sam的帽子提示。 – Friedrich