Arrays with one element within an array

I feel like the answer to this should be simple but I am stumped. I have millions of documents with a few fields that are arrays, and have arrays with one element inside of it. Is there a way to simplify the array field? There is no consistent amount of single element arrays within the touchPointsDate array field.

This is how a field looks:

 "touchPointsDate" : [
        [
            ISODate("2022-09-26T00:00:00.000+0000")
        ],
        [
            ISODate("2022-03-07T00:00:00.000+0000")
        ],
        [
            ISODate("2022-09-05T00:00:00.000+0000")
        ],
        [
            ISODate("2022-03-21T00:00:00.000+0000")
        ],
        [
            ISODate("2022-05-30T00:00:00.000+0000")
        ]

And I would like to simplify it to:

 "touchPointsDate" : [
            ISODate("2022-09-26T00:00:00.000+0000"),
            ISODate("2022-03-07T00:00:00.000+0000"),
            ISODate("2022-09-05T00:00:00.000+0000"),
            ISODate("2022-03-21T00:00:00.000+0000"),
            ISODate("2022-05-30T00:00:00.000+0000")
        ]

Hi @Geoff_Materna and welcome in the MongoDB Community :muscle: !

This is a job for $reduce.

[
  {
    '$set': {
      'touchPointsDate': {
        '$reduce': {
          'input': '$touchPointsDate', 
          'initialValue': [], 
          'in': {
            '$concatArrays': [
              '$$value', '$$this'
            ]
          }
        }
      }
    }
  }
]

The mistake here would be to use $unwind + $group by _id with $push to rebuild the array properly.

Cheers,
Maxime.

1 Like

Amazing!! Yes this is exactly what I was hoping for. Thank you so much!

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.