How to look up documents whose array field includes a particular value?

1,730 views
Skip to first unread message

Nik

unread,
Sep 10, 2010, 4:32:10 AM9/10/10
to Mongoid
Hello,

if I have such a collection:
db.flowers.find()
{id: 123, colors : ['red', 'blue, 'green' ] }

I know in the mongo console I can search for all documents whose
'colors' field includes the value 'blue' by :

db.flowers.find( { colors : 'blue' } )

But I can't seem to find a way to do that in Ruby with Mongoid.

So here are my questions:

1) is there a finder method to achieve the above query?

2) if not, since the javascript query works, how does one inject
javascript query FROM ruby TO mongodb? Could it be that it is done by
something called the map-reduce?

Thank you for reading!

JDeville

unread,
Sep 10, 2010, 11:29:39 AM9/10/10
to Mongoid
flowers.where(:colors.in => "blue") should do it.

You can see how all this stuff works here:
http://mongoid.org/docs/querying/

Good luck

Gregory Moeck

unread,
Sep 10, 2010, 11:37:38 AM9/10/10
to mon...@googlegroups.com
Try:

Class Flower
  field :colors, :type => Array
end

Color.create(:colors => ['red', 'blue', 'green'])

Color.where(:colors.in => ['red'])

Gregory Moeck

unread,
Sep 10, 2010, 11:38:24 AM9/10/10
to mon...@googlegroups.com
Forgot to include Mongoid::Document in the class there :)

Nik

unread,
Sep 10, 2010, 9:59:10 PM9/10/10
to Mongoid
@Gregory, thanks for the response. I haven't yet tried it, but should
it be
@flower = Flower.create(:colors => ['red', 'blue', 'green'])

Flower.where(:colors.in => ['red']) #=> returns the same record as
@flower

@JDeville and @Gregory
I am probably wrong about this, though the syntax ".in" seems to me to
be query "Find all flowers the values of whose colors field are a
subset of _____"
For example, should the above query Flower.where(:colors.in =>
['red']) mean find all flowers which have the colors field to be in
the set ['red']?


On Sep 10, 8:38 am, Gregory Moeck <gmo...@gmail.com> wrote:
> Forgot to include Mongoid::Document in the class there :)
>
> On Fri, Sep 10, 2010 at 8:37 AM, Gregory Moeck <gmo...@gmail.com> wrote:
> > Try:
>
> > Class Flower
> >   field :colors, :type => Array
> > end
>
> > Color.create(:colors => ['red', 'blue', 'green'])
>
> > Color.where(:colors.in => ['red'])
>
Reply all
Reply to author
Forward
0 new messages