how to do range query

2,578 views
Skip to first unread message

songhe yang

unread,
Apr 14, 2011, 3:46:20 AM4/14/11
to Mongoose Node.JS ORM, xuanh...@taobao.com
In mongodb javascript, i can use find({}, {'datetime': {'$gt':
'2011-04-01', '$lt': '2011-04-09'}}) to do range query, but can it do
it in mongoose's find?

Thanks

songhe yang

unread,
Apr 14, 2011, 5:52:58 AM4/14/11
to Mongoose Node.JS ORM
e.g:

In Mongodb, the collection reports has following documents:

db.reports.find()

{ "_id" : ObjectId("4da6992090d211cc097fbb02"), "type" : 0,
"datetime" : "2011-03-30", "amount" : 50760 } { "_id" :
ObjectId("4da6992c90d211cc097fbb03"), "type" : 0, "datetime" :
"2011-03-31", "amount" : 45990 } { "_id" :
ObjectId("4da6993290d211cc097fbb04"), "type" : 0, "datetime" :
"2011-04-01", "amount" : 47430 } { "_id" :
ObjectId("4da6993b90d211cc097fbb05"), "type" : 0, "datetime" :
"2011-04-02", "amount" : 49140 } { "_id" :
ObjectId("4da6994390d211cc097fbb06"), "type" : 0, "datetime" :
"2011-04-03", "amount" : 37260 }

I want to do query using "datetime" in mongoose, so i use the
following code to do it:

var Reports = mongoose.model('Reports');
Reports.find({'datetime': {$gte: '2011-03-30', $lte: '2011-04-01'}},
['type', 'datetime', 'amount']).sort([['datetime']], 1).run (
function(err, reports) { if (err) { console.log("load reports
failed"); } loadCallback(req, res, reports); });

But i can't work!

Sampsa

unread,
May 26, 2011, 3:20:16 AM5/26/11
to Mongoose Node.JS ORM
I am as well trying to utilize the $lte/$gte functionality in queries,
but get a syntax error. My date format is just YYYYMMDD and I'm using
MongoVUE to test my queries, but I have no luck with Mongoose, since I
get a JS Syntax error:

... 'sortdate': { $lte: sortDateNumber });
SyntaxError: Unexpected token )

Just to clarify, sortDateNumber is a valid variable for the match.

mcoolin

unread,
May 26, 2011, 9:32:24 AM5/26/11
to mongoo...@googlegroups.com
It appears your missing some quotes.

Sample is like so:
db.posts.find({"created_on": {"$gte": start, "$lt": end}})

Sampsa

unread,
May 26, 2011, 4:24:00 PM5/26/11
to Mongoose Node.JS ORM
Thanks, I noticed that after a while. Maybe coding when sick isn't the
optimal solution (;

Works like a charm.
Reply all
Reply to author
Forward
0 new messages