I’m currently using the $dateToString
operator to drop milliseconds from datetime fields (the last_updated
fields to be specific.) and I’ve run into an issue.
I have a collection of documents formatted like so:
[
{
"id": "A",
"name": "Meades Park",
"last_updated": ISODate("2022-01-01T00:00:00.000Z"),
"evses": [
{
"id": "AB",
"status": "AVAILABLE",
"last_updated": ISODate("2022-01-01T00:00:00.000Z")
"connectors": [
{
"id": "AAB",
"power_type": "DC",
"last_updated": ISODate("2022-01-01T00:00:00.000Z")
}
]
}
]
},
{
"id": "A",
"name": "Medes Park",
"last_updated": ISODate("2022-01-01T00:00:00.000Z")
}
]
I’m able to format the date fields with the following query:
db.collection.aggregate([
{
$addFields: {
'last_updated': {
$dateToString: {
format: '%Y-%m-%dT%H:%M:%SZ',
date: '$last_updated'
}
}
'evses.last_updated': {
$dateToString: {
format: '%Y-%m-%dT%H:%M:%SZ',
date: '$last_updated'
}
}
'evses.connectors.last_updated': {
$dateToString: {
format: '%Y-%m-%dT%H:%M:%SZ',
date: '$last_updated'
}
}
}
}
])
While this overwrites the evses.last_updated
& evses.connectors.last_updated
fields with the top level last_updated
field, it works well for my use case for the first document.
My issue is that the second document, where the evses
array is absent, this query will create an evses
& connectors object and populate it with the last_updated
field. Is it possible to only convert evses.last_updated
and evses.connectors.last_updated
if the evses
and connectors
arrays exist? I’m aware of the onNull
operator that can be used on $dateToString
, but I’ve not found a way to conditionally stringify a field using it, it seems like it is more for default fields.