Using "or" in Mongoid
17 Jun 2010
Document Databases, Rails, Ruby, Mongoid, MongoDB, and Javascript
Not a very well documented feature here, but, if anyone wants to use something similar to an SQL OR query in MongoDB (using Mongoid) there are two ways, depending on the complexity of the query and the version of Mongo that you have.
Firstly, there is the very easy $in example, represented by saying
scope :in_array, lambda {|arr| where(:in => arr)}
Which is great for the really simple examples – however, for something more substantial, what you’ll need to do is write custom javascript to get what you want
scope :date_constraint, lambda {
today = Date.today
js_date = "new Date(#{today.year}, #{today.month}, #{today.day})"
where("function() {return this.end_date == null || this.end_date >= #{js_date}}")
}
Which is probably not the nicest way of writing such a query, but, its more like a limitation of the Database query language more than a fault with the Mongoid API (which is based on Arel/ActiveModel and fantastic!)
Please enable JavaScript to view the comments powered by Disqus.