Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a range query in Mongoose?

I am currently trying to add prices for each of my Item documents in MongoDB. Many of these prices have ranges, i.e. Item A has a price range of $50-$100. How can I store such ranges in the database and then query based on these values? I was thinking of adding two attributes to each document, lowPrice and highPrice, to respectively hold the lowest of the item's price range and the highest of the item's price range. Then, when I query, I would just query for documents with lowPrice less than or equal to the query price and highPrice greater than or equal to the query price. I feel that there may be a more efficient method of doing this, however. Any suggestions are appreciated!

like image 588
user3802348 Avatar asked Feb 20 '17 03:02

user3802348


Video Answer


1 Answers

Your solution of having a min and max price makes good scene

Have a look at the mongo query comparisons here.

db.test.find({
minNum : { $gte :  50},
maxNum : { $lte :  100}
});

https://docs.mongodb.com/manual/reference/operator/query-comparison/

like image 86
Lwazi Prusent Avatar answered Sep 27 '22 20:09

Lwazi Prusent