Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm new to MongoDB and my requirement is to convert a string date to date. But that particular field is sometimes in date format sometimes in string format.

Effectively, If the date is in string format I want to convert it to date else leave as it is.

Sample data:

paymentDate:2021-11-19T05:36:32.596+00:00

paymentDate:'2021-11-19T05:36:32.596+00:00'

My attempt is

convertedDate: { $cond: { {'$eq': [{$type:"$paymentDate"},9]}, then:"$newField", else:{ $dateFromString: { dateString: '$paymentDate'

You're almost to the answer. Specify the compare value in $type as "date".

db.collection.find({},
  convertedDate: {
    $cond: {
      if: {
        "$eq": [
            $type: "$paymentDate"
          "date"
      then: "$paymentDate",
      else: {
        $dateFromString: {
          dateString: "$paymentDate"

Sample Mongo Playground

References

Available type | $type

Hi @Julien, I rollback your edit as my answer is for query but not update. Anyway thanks for the efforts. – Yong Shun Nov 19, 2021 at 9:06 Post Owner may take note that $dateFromString can be replaced with { '$toDate': '$paymentDate' } as mentioned by @ray. – Yong Shun Nov 19, 2021 at 9:08 Because 9 is not a valid type, check out the reference link I shared to you for list of types in MongoDB. – Yong Shun Nov 19, 2021 at 11:06

If you are using MongoDB 4.2+, you may simply use $toDate to convert your field in an update with aggregation pipeline operation.

db.collection.update({},
    "$set": {
      "paymentDate": {
        "$toDate": "$paymentDate"

Here is the Mongo playground for your reference.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.