Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb date format

I was doing bulk insert into MongoDB using NodeJs (native -driver). I have date field in the data. Is there anyway to store the date field as Date rather than String?

I have date in dd/mm/yyyy format. In current scenario I attain the result by iterating through the bulk data converting the date into mm/dd/yyyy format, then create new Date and save.

Since the iteration takes too much time as amount of Data increases; is there any other method to do it?

like image 702
Okky Avatar asked Nov 03 '22 19:11

Okky


1 Answers

There is no way to tell mongodb (mongoimport) to convert the string 'dd/mm/yyyy' to a $date type during the import.

What you can do is to change the type after the bulk insert. You can run this code at the mongodb shell (mongo):

    db.your-collection-name.find().forEach(function(element){

       var parts = element.date.split("/");

       //reduce month by 1 because in javascript january is 0
       element.date = new Date(parts[2], parts[1]-1, parts[0]);

       db.your-collection-name.save(element);

    });
like image 67
Alex Baban Avatar answered Nov 11 '22 05:11

Alex Baban