0

I am trying to query a collection in Mongo database, to get all record with Time field in a date range. Time is defined as Date in database.
My environment: Node.js, Express, Jade, javascript.

This is the javascript code:

var query = {};
var timeQuery = {};
timeQuery["$lt"] = new Date().toISOString();
query["Time"] = timeQuery;
console.log(query);
db.model('testruns').find(query).exec(function (err, testruns) {
    console.log(testruns.length);
    // doing something
});

the result printed to console:

{ Time: { '$lt': '2014-10-30T15:04:39.256Z' } }
0

The query returns 0 results (there should be more)

By the way... Running date queries from RoboMongo returns results, just the wrong ones. for example:

db.testruns.find({Time : {"$gte" : new Date("2014-10-30T15:13:37.199Z")}})

returns all records.

What I tried: This one, that one, another one, mongoose documentation of course, and many more results from google.

Most of them give the same answer, none of them works for me. HELP!

Community
  • 1
  • 1
Keren
  • 407
  • 2
  • 7
  • 20

2 Answers2

0

as far I see you are not including the field to reference in the query, can you try this: I assume your field name is 'time'

var date = new Date(); //or the date you want to compare
db.model('testruns').find({"Time":{"$lt":date}}).exec(function (err, testruns) {
    console.log(testruns.length);
    // doing something
});
pedrommuller
  • 15,741
  • 10
  • 76
  • 126
0

The problem was related to a schema definition, not directly to this code. The code of the query was correct. a schema definition had this field(Time) as String, which caused MongoDB to try and find a string in a date field...

Keren
  • 407
  • 2
  • 7
  • 20