MongoDB convert field in array of documents to different data type

Viewed 474

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.

1 Answers

The regular update query can't allow aggregation operators in update part, and the second docsArray is an array so regular update query won't work,

try update with aggregation pipeline starting from MongoDB 4.2,

  • $map to iterate loop of docsArray array and convert createdDate from string to date type
db.collection.update(
  { _id: "12345" },
  [{
    $set: {
      docsArray: {
        $map: {
          input: "$docsArray",
          in: { createdDate: { $toDate: "$$this.createdDate" } }
        }
      }
    }
  }]
)

Playground

Related