This is how I went about to query for one specific element.
results << read_db.collection("users").find(:created_at => {:$gt => initial_date}).to_a
Now, I am trying to query by more than one.
db.inventory.find({ $and: [ { price: 1.99 }, { qty: { $lt: 20 } }, { sale: true } ] } )
Now how do I build up my query? Essentially I will have have a bunch of if statements, if true, i want to extend my query. I heard there is a .extend command in another langue, is there something similar in ruby?
Essentially i want to do this:
if price
query = "{ price: 1.99 }"
end
if qty
query = query + "{ qty: { $lt: 20 } }"
end
and than just have
db.inventory.find({ $and: [query]})
This syntax is wrong, what is the best way to go about doing this?
You want to end up with something like this:
Note that I’ve switched to the hashrocket syntax, you can’t use the JavaScript notation with symbols that aren’t labels. The value for
:$andshould be an array of individual queries, not an array of strings; so you should build an array:BTW, you might run into some floating point problems with
:price => 1.99, you should probably use an integer for that and work in cents instead of dollars. Some sort of check thatpartsisn’t empty might be a good idea too.