pat*_*ler 9 mongodb aggregation-framework
我们试图将一个字符串数组'连接'到聚合内的单个字符串.
给出以下数据集:
收集1:
{
id: 1234,
field: 'test'
}
Run Code Online (Sandbox Code Playgroud)
收集2:
{
id: 1111,
collection1_id: 1234,
name: 'Max'
},
{
id: 1112,
collection1_id: 1234,
name: 'Andy'
}
Run Code Online (Sandbox Code Playgroud)
当前结果(查找后等):
{
id: 1234,
field: 'test',
collection2: ['Max', 'Andy']
}
Run Code Online (Sandbox Code Playgroud)
期望的结果:
{
id: 1234,
field: 'test',
collection2: 'Max, Andy'
}
Run Code Online (Sandbox Code Playgroud)
是否有可能将'collection2'加入单个字符串?我们尝试过,$concat但它只接受字符串.
Fri*_*ich 12
你走在正确的轨道上.
只需在舞台上添加$ reduce超过$ concat即可$project.
'collection2': {
'$reduce': {
'input': '$collection2',
'initialValue': '',
'in': {
'$concat': [
'$$value',
{'$cond': [{'$eq': ['$$value', '']}, '', ', ']},
'$$this']
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:我们使用$ cond来阻止,串联中的前导.你也可以使用$ substrCP之前$reduce作为替代$cond.
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
3547 次 |
| 最近记录: |