Update date values in docs of Mongo Collection to ISODate format

156 Views Asked by At

I have a Collection in Mongo data store, for which I have docs which have a value as below.

{
    "_id" : "ABC-98765432",
    "Prospects" : [ 
        {
            "emailAddress":"[email protected]",
            "dateOfBirth" : Date(-62135751600000)
        }, 
        {
            "emailAddress":"[email protected]",
            "dateOfBirth" : ISODate("2008-10-08T04:00:00.000Z")
        }
    ]
}

The value for the dateOfBirth field is not in ISODate format for one of the elements of the Prospects array field in the document.

I have many docs like this in my collection, which have the invalid value in different positions of the Prospects array field.

Also, the value , Date(-62135751600000) is the same in all the docs which are incorrect.

I am looking for a way to convert this date value to ISODate format, if not at-least set it to null value.

Is there a way to update those docs which have this invalid value for the date field in the collection with the ISODate value.

1

There are 1 best solutions below

1
parastoo taleiniya On

You can write a function to do this job for you. find all wrong documents and update them:

const updateWrongDocuments =  () => {
  return new Promise(async(resolve, reject) => {
    try{
      let docs = await collection.find({"Prospects.dateOfBirth" : Date(-62135751600000)});
      for(let doc of docs) {
        for(let Prospect of doc.Prospects) {
          if(Prospect.dateOfBirth.equals(Date(-62135751600000))){
            Prospect.dateOfBirth = new Date();
          }
        }
        doc = await doc.save();
      }
      resolve('successful update!');
    }
    catch(err){
      reject(err);
    }
  });
}