Home > Net >  MongoDB $type check on a field
MongoDB $type check on a field

Time:11-20

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 try is

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

CodePudding user response:

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.

CodePudding user response:

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

  • Related