4

I have a table called " Stat " in my MongoDB database in Rails 3 .

In that table, there is an array field called "services" .

I want to find all Stats that have a services array that contains the value "lights" .

I want to do something like this :

@stats = Stat.all
@stats1 =  @stats.where("services contains lights")
Rails.logger.info "result:  #{@stats1.count}  " 

I've tried various things and Googled it extensively, found some leads but nothing that seems to work. I have four records that should match this query but the above returns a zero set.

Is what I want to do possible in rails 3 / mongo ?

1
  • What Object Mapper are you using to access MongoDB? If you are using the native Ruby driver it does not implement ActiveRecord; you would instead be doing a find() on a collection. Commented Aug 11, 2012 at 2:37

2 Answers 2

4

Try this,

@stats = Stat.all

@stats1 =  @stats.where("'lights' = ANY (services)")
Sign up to request clarification or add additional context in comments.

Comments

1

Ok I found the answer to this question:

@stats =  @stats.where(:services.in =>['lights'] )

and I also found by poking around that the inverse is:

@stats =  @stats.where(:services.nin =>['lights'] )

nin instead of in

2 Comments

I understand this is old, but maybe you could link to where you found your answer?
I actually think I got the answer to this by asking one of my co-workers at the time, and then fiddling with it to find the "nin" variation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.