0

I have a date that is in this format in my MongoDB database.

{
      "_id": ObjectId("5682e899f326d45c821d8b9b"),
      "City": "Atlanta",
      "Date": "12/5/02",
      "Temp": 78.5,
}

I would like to convert this to ISO date so I could sort on date in my database. What would be the best way to do this with an update command with PyMongo or JavaScript.

styvane
  • 59,869
  • 19
  • 150
  • 156
Yolo49
  • 489
  • 2
  • 7
  • 14

3 Answers3

1

Mongo has moved on quite a bit since I last used it but as far as I know, as has been suggested elsewhere you are going to have to load and update each record in turn.

You have two problems. The first is that your date format is ambiguous. The example date you give will have different values depending on the locale of the system used to parse it as a date. In the US it is (I think) December the 5th 2002. On my side of the atlantic though it will parse as 12th May 2002. Funtimes.

Assuming you know the intented format of each date then in node you could use moment.js to parse each date to a fixed format for example

let date = moment(document.Date, "D/M/YY");

and then output as an ISO date using

document.Date = date.toISOString();

or if you are being good, and doing it non-destructively

document.ISODate = date.toISOString();

although now you have two dates to look after...

Andrew
  • 698
  • 5
  • 13
0

You will need to iterate over the entire result set, and update each document individually like so:

var f = function(e) {
    var arr = e['Date'].split("/");

    //assuming "Date" field was formatted as "YY/MM/DD"
    var date_obj = new Date(arr[0], arr[1], arr[2]);

    db.your_collection.update({_id: e['_id']}, {$set: {date_obj: date_obj}});    
}


db.your_collection.find().forEach(f)

If you want to remove your old field, you can run the following:

db.your_collection.update({}, {$unset: {Date: 1}}, {multi:true});

But don't do that until you are sure your dates were converted correctly.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
-1

I think, you should first retrieve the records and use a loop to change all. Then you should parse the data to construct a Date object to convert to mongo date.

var value = "12/5/02";
var parts = value.split("/");
var dt = new Date("20"+parts[2], parseInt(parts[1])-1, parts[0]);

If you are using nodejs, check this too.

Edit: I assumed 12=day, 5=month.

Community
  • 1
  • 1
abeyaz
  • 3,034
  • 1
  • 16
  • 20