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
{}around the$reducein order to be a valid object expression. You should be getting an error like that from the mongo shell. Also justinput: { $concatArrays: [ ['$field1'], '$fruits'] }using just the$reduceis much cleaner than nesting the result within another$concat.