Mongoose greater than and equal
Query.prototype.gt
method is the same as using "greater than" operator.
In your case, you have to use gte
method that returns exactly what you need - results that are greater or equal to given value:
let x = 89;
query.find()
.where('marks')
.gte(x)
.exec();
Also, as another answer mentioned, you can always use native MongoDB operator $gte
, however Mongoose offers more intuitive approach with its chaining Query API, as above.
Also, if you're using Mongoose with Promises or async/await
, don't forget to add
exec()
at the end - this will convert thenable-compatible Query result to a fully featured Promise, e.g.:
let x = 89;
find().where('marks').gte(x).exec()
.then(() => {/* rest of handling*/})
.catch(() => { /* error handling */});
The same code using async/await
:
async function getResultsGreaterThan(x) {
const results = await find().where('marks').gte(x).exec();
console.log(results);
return results;
}
getResultsGreaterThan(89);
More on Mongoose chainable Query API can be found in rather solid official docs https://mongoosejs.com/docs/api/query.html
I don't know what version of mongodb you are using. But this is what available in the latest releases.
$gte
selects the documents where the value of the field is greater than or equal to (i.e. >=) a specified value
query.find( { marks: { $gte: 89} } )
Here
Simply use
.gte(upperlimit)
for greater than equal to and
.lte(lowerlimit)
for less than equal to.
Remember upperlimit and lowerlimit should be numeric.