I need to change the type of stored array values from String to ISODate in MongoDB. The process should change the stored types, not just project them out in a new format.
The document structure is as follows with the target values nested in an array at absences[].date
.
[{
"id": 3086,
"first": "Knox",
"last": "Keith",
"middle": "Kent",
"absences": [{
"date": "Wed Nov 28 2018 15:12:09 GMT+0000 (UTC)",
"code": "X",
"type": "E",
"isPartial": false
},
{
"date": "Wed Dec 26 2018 12:35:46 GMT+0000 (UTC)",
"code": "X",
"type": "E",
"isPartial": false
}
]
}]
I can change the value of those fields (but not the type) easily with $set:
db.students.update(
{ },
{ $set: { "absences.$[].date" : "changed" } },
{ multi: true }
)
@JohnnyHK shared this example of changing a String to ISODate, but this only works for top-level objects (not arrays).
db.snippets.find({created_at: {$not: {$type: 9}}}).forEach(function(doc) {
doc.created_at = new Date(doc.created_at);
db.snippets.save(doc);
})
I'd be grateful for advice about combining these two strategies, i.e. looping through the absences
array to convert the date
field from String to ISODate.