MongoDB Aggregation将字符串数组连接到单个字符串 [英] MongoDB Aggregation join array of strings to single string

查看:502
本文介绍了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,但是它只接受字符串.

解决方案

您在正确的轨道上.

只需在 $ reduce

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

阶段中的href ="https://docs.mongodb.com/manual/reference/operator/aggregation/concat/#exp._S_concat" rel ="noreferrer"> $ concat .

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

注意:我们使用 $ cond 来防止在连接中使用前导,. 您还可以在$reduce之前使用 $ substrCP 替代$cond.

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

Given is the following dataset:

Collection 1:

{
  id: 1234,
  field: 'test'
}

Collection 2:

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

The current result (after lookup etc.):

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

The desired result:

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

Is it somehow possible to join the 'collection2' to a single string? We've tried with $concat but it only accepts strings.

解决方案

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.

这篇关于MongoDB Aggregation将字符串数组连接到单个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆