2

I would like to do this from the mongo shell. Basically I want to change the way times are stored in my current database.

Right now my 'time' field is storing a string that looks like 'Thu Oct 11 2012 15:27:58 GMT-0500 (CDT)', but I would like to run a Date.parse('Thu Oct 11 2012 15:27:58 GMT-0500 (CDT)') so that the unix timestamp is stored instead.

I want to do this across the board for all current entries since I will just be using the unix timestamp in the future.

Thanks

Robeezy
  • 2,424
  • 3
  • 22
  • 28

1 Answers1

5

How about:

var c = db.collection.find();
while (c.hasNext()) {
  object = c.next(); 
  time = Date.parse(object.time);
  db.collection.update({_id: object._id}, {$set: {'time': time}});
}

Before executing it, I had the following:

db.times.find()
{ "_id" : ObjectId("50773daa77f428a7e4cd226b"), "time" : "Thu Oct 11 2012 15:27:58 GMT-0500 (CDT)" }

After executing it, it looks like this:

db.times.find()
{ "_id" : ObjectId("50773daa77f428a7e4cd226b"), "time" : 1349987278000 }

Hope this helps!

peshkira
  • 6,069
  • 1
  • 33
  • 46
  • Dude you are awesome! I wasn't aware of the hasNext()/next() functions since I'm just usually interacting with mongo using mongoose/nodejs. Thanks! – Robeezy Oct 11 '12 at 22:55
  • glad it resolves it. If you don't want to type it every time, or if you have longer functions, you can just create a .js script and pass it as parameter to the `mongo` tool – peshkira Oct 12 '12 at 07:05