Advanced range query in mongodb?
-
There are two fields in one collection "max" and "min". I have two integers X and y. I want to perform a query like this on the collection; find all the rows whose 'min'-y <= X <='max'+y. How can i do that [updated] in pymongo?
-
Answer:
It is possible to pass the exact query( 'min'-y <= X <='max'+y) in javascript as suggested by Jared; db.collection.find("this.min - 5 <= 10 && this.max + 5 >= 10");But it's not possible to query in the same fashion using pymongo. In pymongo, rewriting the condition to 'min' <= X + y and X - y <= 'max'db.collection.find({"min": {"$lte": X + y}, "max": {"$gte": X - y}})does the work.
Answer Wiki at Quora Visit the source
Other answers
You can use a Javascript expression that will get evaluated for each document in your collection. For your example, if X=10 and y=5, you could have a query that looks like db.collection.find("this.min - 5 <= 10 && this.max + 5 >= 10"); The documentation can be found at http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-JavascriptExpressionsand%7B%7B%24where%7D%7D
Jared Winick
You can rewrite the condition to: 'min' <= X + y and X - y <= 'max' You can then pass the condition to pymongo: db.collection.find({"min": {"$lte": X + y}, "max": {"$gte": X - y}})
Ivo Danihelka
Related Q & A:
- How to query by datetime in Doctrine MongoDB ODM?Best solution by Stack Overflow
- How to hybrid Mysql and MongoDB in Play framework?Best solution by Stack Overflow
- How to convert sql query to Hibernate Criteria query?Best solution by Stack Overflow
- How to convert my SQL query to MS Access query?Best solution by Stack Overflow
- How to convert SQL query to LINQ query?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.