Change String date to ISO date in MongoDB?

TB.M picture TB.M · Jan 23, 2017 · Viewed 7.7k times · Source

In MongoDB, I have a document with a field called "date" and that is in array.

  {
"_id" : ObjectId("587627a2125a730f78a20859"),
"data" : [
    {
        "Number" : "359983007479839",
        "date" : "2016-02-10T21:56:33.000Z"
    }
] 

after that I run this script:

db.dummy.find().forEach(function(doc){
doc.mongodbdate = ISODate(doc.mongodbdate);
db.dummy.save(doc);
})

And its giving me below output;

{
"_id" : ObjectId("588724ba2746360c04a51e4b"),
"data" : [
    {
        "Number" : "359983007479839",
        "mongodbdate" : "2016-02-12T18:01:06.000Z"
    }
],
"mongodbdate" : ISODate("2017-01-24T15:26:24.537+05:30")
}

I tried this also:

var bulk = db.dummy.initializeUnorderedBulkOp(),
count = 0;

db.dummy.find().forEach(function(doc) {
bulk.find({ "_id": doc._id }).updateOne({
    "$set": { "mongodbdate": ISODate(doc.mongodbdate) }
})
count++;
if (count % 1000 == 0) {
    // Execute per 1000 operations and re-init
    bulk.execute();
    bulk = db.dummy.initializeUnorderedBulkOp();
}
})

its throws Error: "message" : "invalid ISO date"

I want to convert that string date into ISO date.I have changed with some code but its adding new date with ISO format but I want to update which is already available no need to insert new one. One solution I got on stackoverflow also, but that is adding new field in my document i think it is because of array,I want to update my existing one.

Answer

hackel picture hackel · Jun 27, 2017

You just need to modify your code to loop over the array as well.

db.dummy.find().forEach(function (doc) {
  doc.data.forEach(function (currentValue, index) {
    doc.data[index].mongodbdate = ISODate(currentValue.mongodbdate);
  });
  db.dummy.save(doc);
})