mongodbdatetimestamptype-conversionbson

Convert BSON ISODate to NumberLong in MongoDB


I have a collection in MongoDB that has created fields with values currently stored as a BSON ISODate object. I want to convert all of those to NumberLong objects containing a timestamp.

First I tried this (in Mongo shell):

db.collection.find( { "created" : { "$type" : 9 } } ).forEach( function (x) {   
  x.created = new NumberLong(x.created);
  db.collection.save(x);
});

JavaScript execution failed: Error: could not convert "Tue Mar 18 2014 18:11:21 GMT-0400 (EDT)" to NumberLong

Apparently a date string cannot be cast as a long...fair enough. Then I tried this, thinking I could make use of the Javascript Date object's UTC method:

db.collection.find( { "created" : { "$type" : 9 } } ).forEach( function (x) {
  x.created = new Date(x.created).UTC();
  db.collection.save(x);
});

JavaScript execution failed: TypeError: Object Tue Mar 18 2014 18:11:21 GMT-0400 (EDT) has no method 'UTC'

I've tried several other variations, but nothing has worked yet. Any help would be greatly appreciated!


Solution

  • To access the underlying numeric value of the Date, you can call getTime() on it:

    x.created = new NumberLong(x.created.getTime());