MongoDB Aggregation join array of strings to single string

前端 未结 4 941
长发绾君心
长发绾君心 2021-02-12 15:14

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

Given is the following dataset:

Collection 1:

{
  id: 123         


        
4条回答
  •  耶瑟儿~
    2021-02-12 15:22

    Sometimes it's easiest to use JavaScript:

    db.getCollection('Collection1').aggregate([
    {
       $lookup:
         {
           from: 'Collection2',
           localField: 'id',
           foreignField: 'collection1_id',
           as: 'col2'
         }
    }]).map((e) => ({
      id: e.id,
      field: e.field,
     collection2: Array.isArray(e.col2) &&
       e.col2.reduce((arr, el) => {
         arr.push(el.name);
        return arr;
      }, []).join(', ')
    }))
    

提交回复
热议问题