2016-07-14 113 views
3

我們試圖將一個字符串數組「連接」到聚合中的單個字符串。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

添加您到目前爲止的代碼 –

回答

0

要扁平化該數組,您需要將流程轉移到客戶端。

mongo將在新版本中提供一些新的展平選項,但afaik它將是算術平面(平均,最小,最大....)。

1

你在正確的軌道上。

只需在$project階段添加$reduce超過$concat

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

注意:我們在$cond防止串聯的領先,。 您也可以在$reduce之前使用$substrCP作爲$cond的替代選項。

希望這會有所幫助!

+0

給Sam的帽子提示。 – Friedrich