I have a document with an array of documents, where I'd like to convert a field in those documents to another data type. In my case I have a date string I'd like to recast as a date object, and I know the index of the array item I'd like to update:
{
"_id": 12345,
"docsArray": [
{ "createdDate": "2008-01-12T07:36:45-08:00" },
{ "createdDate": "2008-01-12T07:36:45-08:00" }
]
}
When I run the following:
db.collection.update(
{ "_id": 12345 },
{
"$set": {
"docsArray.0.createdDate": { "$toDate": "$docsArray.0.createdDate" },
},
}
)
I get:
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 52,
"errmsg" : "The dollar ($) prefixed field '$toDate' in 'docsArray.0.createdDate.$toDate' is not valid for storage."
}
})
What am I doing wrong, and is there a better way to do this? I'd like to do this using the $set operator and explicitly referencing the index of the array item to update if possible.