mongoose node.js, query with $lt and $gt not working


Question

I want to get all the pupils whose last mark is between 15 and 20. To do so, I perform the following query in my mongoDB using mongoose: The models are working fine (all the other queries are ok).

Pupils.find({"marks[-1].value": {'$lt' : 20 }, "marks[-1].value" : { '$gt' : 15 }}, function(err, things){

This is not working, is there something I missed ?

* UPDATE *

I found something like:

Pupils.find({ "marks[-1].value": {$gt : 15, $lt : 20}});

But this does not work either. Is there a way to get the last mark of the marks array in this case ?

1
2
4/12/2011 7:17:28 AM

Accepted Answer

Lets consider your Pupils collection:

Pupils 
{
  _id,
  Marks(integer),
  LatestMark(int)
}

I suggest to add latest mark into Pupil document(as you can see at the document above), and update it each time when you adding new mark into nested collection. Then you will able to query on it like this:

db.Pupils.find({ "LatestMark": {$gt : 15, $lt : 20}});

Also you can query latest mark using $where, but be care because:

Javascript executes more slowly than the native operators, but is very flexible

5
4/12/2011 10:17:16 AM

I believe it's not working because the embedded collections in mongo are accessed like this: "marks.0.value", although I haven't used mongoose.

Unfortunately for your scenario, I do not think there is a way to use negative indexing. (Mongo doesn't guarantee a preserved natural order unless you use a capped collection anyway though)

You may be able to accomplish this using Map/Reduce or a group command

http://www.mongodb.org/display/DOCS/MapReduce


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon