Tommy B.
Tommy B.

Reputation: 3639

Find using $lt and $gt with javascript Dates

I'm trying to fetch results from a MongoDB collection. Here's an example of it:

{ "entryDate" : "2012-10-14T00:00:00.000Z", "amount" : 1, "cardId" : "50786621e3b983f1078d0bc9", "_id" : ObjectId("507a17354c6cbd6a4b000001"), "addedDate" : "Sat Oct 13 2012 21:36:53 GMT-0400 (EDT)" }
{ "entryDate" : "2012-10-10T00:00:00.000Z", "amount" : 21, "cardId" : "50786639e3b983f1078d205e", "_id" : ObjectId("507a17394c6cbd6a4b000002"), "addedDate" : "Sat Oct 13 2012 21:36:57 GMT-0400 (EDT)" }
{ "entryDate" : "2012-10-09T00:00:00.000Z", "amount" : 1, "cardId" : "50786639e3b983f1078d205e", "_id" : ObjectId("507a25e46af510804c000002"), "addedDate" : "Sat Oct 13 2012 22:39:32 GMT-0400 (EDT)" }
{ "entryDate" : "2012-10-08T00:00:00.000Z", "amount" : 12, "cardId" : "50786621e3b983f1078d0bc9", "_id" : ObjectId("507a2603b7a095824c000003"), "addedDate" : "Sat Oct 13 2012 22:40:03 GMT-0400 (EDT)" }
{ "entryDate" : "2012-10-08T00:00:00.000Z", "amount" : 1, "cardId" : "507865e1e3b983f1078ceb3f", "_id" : ObjectId("507a2667b7a095824c000004"), "addedDate" : "Sat Oct 13 2012 22:41:43 GMT-0400 (EDT)" }
{ "entryDate" : "2012-10-15T00:00:00.000Z", "amount" : 2, "cardId" : "50786621e3b983f1078d0bc9", "_id" : ObjectId("507a48c170b1a26f4f000001"), "addedDate" : "Sun Oct 14 2012 01:08:17 GMT-0400 (EDT)" }

Here's the query I'm trying to execute: (this is collection)

// (these are JS Date objects)
// start =  Sun Oct 7 2012 13:22:02 GMT-0400 (EDT)
// end =  Sat Oct 20 2012 13:22:02 GMT-0400 (EDT)

this.find({ cardId: cardId, entryDate: { $lt : start, $gt : end } }).toArray(function(err, entries) { console.log(err, entries) });

But unfortunately, it always return [] and no errors.

Any ideas? I'm surely doing something wrong, but I've been searching for so long that I'm askign for your help.

Thanks a lot nad have a nice day!

Upvotes: 3

Views: 2801

Answers (2)

Sergey Rybalkin
Sergey Rybalkin

Reputation: 3026

Try this:

this.find({ cardId: cardId, entryDate: { $lt : start, $gt : end } }).toArray(function(err, entries) { console.log(err, entries) });

Here is how I tested it. Insert scripts looked like this one:

db.samples.insert({ "entryDate" : new Date(2012, 10, 9), "amount" : 1, "cardId" : "50786639e3b983f1078d205e" })

Lookup query is this one:

db.samples.find({ entryDate: { $gt : new Date(2012, 10, 7), $lt : new Date(2012, 10, 20) } }).count();

Upvotes: 3

JohnnyHK
JohnnyHK

Reputation: 311945

Your date range is backwards. It should be:

this.find({ cardId: cardId, entryDate: { $gt : start, $lt : end } })
    .toArray(function(err, entries) { 
        console.log(err, entries) 
    }
);

Upvotes: 1

Related Questions