How do I perform this ActiveRecord query?

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

Was this solution helpful to you?

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:

Just Added Q & A:

Find solution

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.