Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 923
Luc Avatar asked Oct 16 '25 13:10

Luc


1 Answers

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

like image 163
Andrew Orsich Avatar answered Oct 18 '25 08:10

Andrew Orsich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!