0

I have a mongo collection, and an example of the document that looks like this:

"_id" : ObjectId("5a0625b5849c823f77ba8d2b"),
"start_datetime" : ISODate("2017-07-01T00:00:00Z"),
"cdn_400_%_lin_hls" : 0,
"cdn_400_%_lin_ss" : 0,
"cdn_400_%_vod_hls" : 0

I am trying to aggregate based on a match on the "start_datetime" field, which contains ISODate date object in it, using javascript. Below is my code:

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/mydb';

MongoClient.connect(url, function(err, db) {

db.collection('my_collection', function(err, collection) {

    collection.aggregate(
        {'$match':{'start_datetime': new Date("2017-07-01T00:00:00Z")}},
        function(err, data){

            if(err)
                throw err;

            console.log(data);
        }
    );
});
});

Below is the result when I ran the script:

_id: 5a0625b5849c823f77ba8d2b,
start_datetime: Fri Jun 30 2017 18:00:00 GMT-0600 (MDT),
'cdn_400_%_lin_hls': 0,
'cdn_400_%_lin_ss': 0,
'cdn_400_%_vod_hls': 0,

My questions:

  1. Why did the result show start_datetime: Fri Jun 30 2017 18:00:00 GMT-0600 (MDT) instead of "start_datetime" : ISODate("2017-07-01T00:00:00Z")?

  2. How can I make it so that the result shows "start_datetime" : ISODate("2017-07-01T00:00:00Z"), which is what's actually saved in the collection (basically, I want the ISODate object not the formatted string of the date)?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
wi3o
  • 1,467
  • 3
  • 17
  • 29
  • I should've mentioned that I have tried the toISOString(), but still gave the same results. Thanks @Neil Lunn – wi3o Nov 14 '17 at 23:11
  • No it does not. Just for the record There's also a Gold MongoDB badge in the swag for me and that means "I know what I'm talking about". `toISOString()` or `toJSON()` for that matter will give you `"2017-07-01T00:00:00.000Z"` just like it should. The reason you don't see `ISODate()` is because that a JavaScript Prototype "specific to the mongo shell" and nothing to do with how MongoDB actually stores it. It's not an ISODate but a BSON Date, and that's just the way the shell has a function to "display it pretty". So for general JavaScript, you use the standard methods from `Date`. – Neil Lunn Nov 14 '17 at 23:25
  • The short one is of course `console.log(JSON.stringify(data, undefined,2))`. That calls `.toJSON()` and produces the "ISO string" like it should. – Neil Lunn Nov 14 '17 at 23:29

0 Answers0