1

I am trying to query MongoDb using a date range in my FindOne statement, but I cannot get it to work. I am using the Nodejs native driver. I've tried various options, but nothing is returning the expected record.

Here is my pseudo-code -

console.log(sDate);                    // displays  Fri Jun 20 2014 10:00:00 GMT+1000 (AUS Eastern Standard Time)
var sDateISO = sDate.toISOString();
console.log(sDateISO);                 // displays  2014-06-20T00:00:00.000Z 

// all of these return null object
db.collection('events').findOne(
  { eventStartDate: { $lte: new Date(sDate)}},
  function(err, obj) { console.dir(obj); }        // displays  null
);

db.collection('events').findOne(
  { eventStartDate: { $lte: (sDate) }},
  function(err, obj) { console.dir(obj); }        // displays  null
);

db.collection('events').findOne(
  { eventStartDate: { $lte: new Date(sDateISO) }},
  function(err, obj) { console.dir(obj); }        // displays  null
);

db.collection('events').findOne(
  { eventStartDate: { $lte: (sDateISO) }},
  function(err, obj) { console.dir(obj); }        // displays  null
);

However, if I run this in RoboMongo, the record is returned as expected -

enter image description here

==========

UPDATE

My problem was elsewhere in my code -- I had a type mismatch problem in a separate parameter passed to the FindOne query.

As stated in the documentation, and confirmed by Christian P below, I can use my Javascript date object sDate in the FindOne query directly.

I used a typeOf function (found here) to confirm sDate is indeed a Date object.

So, after inspecting all other variables in my actual code, I found the problem elsewhere, unrelated to the Date object / parameter.

Community
  • 1
  • 1
mjmoody383
  • 358
  • 6
  • 19

1 Answers1

1

ISODate is a wrapper around Date object in the MongoDB shell. Robomongo embeds the same JavaScript engine as mongo shell, that's why your query works in RoboMongo.

To query the date range you can simply use the Date object in your query:

db.collection('events').findOne(
  { eventStartDate: { $lte: sDate}},
  function(err, obj) { 
      console.dir(obj); 
  }
);
Christian P
  • 12,032
  • 6
  • 60
  • 71