2

I need to concat values of an array with some other fields.

Given is the following dataset :

{
  _id: ObjectId("1234"),
  field1: "test1",
  field2: "test2",  
  collection2: ['apple', 'banana', "orange"]  
}

I want this result :

{
  _id:ObjectId("1234")
  fruits:"test1 apple banana orange"
}

I got this so far (in $project stage) :

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

I don't really understand why this isn't working, any idea ?

Thanks

1
  • You are missing the wrapping {} around the $reduce in order to be a valid object expression. You should be getting an error like that from the mongo shell. Also just input: { $concatArrays: [ ['$field1'], '$fruits'] } using just the $reduce is much cleaner than nesting the result within another $concat. Commented Mar 16, 2019 at 21:47

1 Answer 1

1

Try something like below:

db.fruits.aggregate([
    {
        $project: {
            values: {
                $reduce: {
                    input: '$collection2',
                    initialValue: '',
                    in: {
                        $concat: ['$$value',' ','$$this']
                    }
                }
            },
            field1: 1
        }
    },
    {
        $project: {
            'fruits': { '$concat': [ '$field1', '$values'] }
        }
    }
    ])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.