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

2024-03-29

我们正在尝试将字符串数组“连接”到聚合中的单个字符串。

给出的是以下数据集:

集合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但它只接受字符串。


你走在正确的轨道上。

只需添加$reduce https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/#exp._S_reduce over $concat https://docs.mongodb.com/manual/reference/operator/aggregation/concat/#exp._S_concat在你的$project stage.

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

注意:我们使用$cond https://docs.mongodb.com/manual/reference/operator/aggregation/cond/#exp._S_cond以防止领先,在串联中。 你也可以使用$substrCP https://docs.mongodb.com/manual/reference/operator/aggregation/cond/#exp._S_cond before $reduce作为替代$cond.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MongoDB聚合将字符串数组连接到单个字符串 的相关文章

随机推荐