2023-03-29

MongoDB - Array of strings to comma-separated string, with no comma after the last element

 db.COLLECTION_NAME.aggregate([

    {$addFields: {

        "CONCATENATED_STRING": {$reduce: {

            "input": "$ARRAY_OF_STRINGS_FIELD_NAME",

            "initialValue": "",

            "in": {

                "$concat": [

                    "$$value",

                    {"$cond": [{"$eq": ["$$value", ""]}, "", ", "]}, 

                    "$$this"

                ]

            }

        }}

    }}    

]);

MongoDB - Array of strings to comma-separated string

 db.COLLECTION_NAME.aggregate([

    {$addFields: {

        "CONCATENATED_STRING": {$reduce: {

            "input": "$ARRAY_OF_STRINGS_FIELD_NAME",

            "initialValue": "",

            "in": {

                "$concat": [

                    "$$value",                    

                    "$$this",

                    ", ",

                ]

            }

        }}

    }}    

]);