Convert all occurrences of DateTime in a document to String, including arrays

Given the sample document (below), would like to convert all occurrences of field timestamp into string without using an unwind/group stage. The timestamp field appears in more than one array (e.g.: array1, array2, etc.), so need something generic.

I can convert it using the the project stage when not using an array as shown below.

    "array1.pollClosing.first.timestamp": {
        "$dateToString": {
            "format": "%Y-%m-%dT%H:%M:%SZ",
            "date": "$states.pollClosing.first.timestamp"
        }
    },
SAMPLE DOCUMENT

{
    "_id" : "20221108",
    "array1" : [
        {
            "id" : "11",
            "pollClosing" : {
                "first" : {
                    "timestamp" : ISODate("2022-11-09T00:00:00.000+0000")
                }
            }
        },
        {
            "id" : "13",
            "pollClosing" : {
                "first" : {
                    "timestamp" : ISODate("2022-11-09T03:00:00.000+0000")
                }
            }
        }    ]
}

Thanks
P

Take a look at $map.

You input: will be $array1.

Your in: expression will use $dateToString like you did.

1 Like