Query on Mongoid Hash Field

14,920
Person.where('things.tv' => 'Samsung').first

This is where Mongoid and MongoDB really shine. Mongoid's Criteria methods (Person.where, Person.any_of, Person.excludes, etc.) will give you much more flexibility than the ActiveRecord-style finders (passing a :conditions hash to Person.find, Person.first, etc.)

Mongoid's site has some great documentation on how to use Criteria:

http://mongoid.org/en/mongoid/docs/querying.html

Share:
14,920
JP Richardson
Author by

JP Richardson

https://www.exodus.com - all-in-one app to secure, manage and exchange blockchain assets like Bitcoin and Ethereum.

Updated on June 05, 2022

Comments

  • JP Richardson
    JP Richardson about 2 years

    I want to query on a Hash field for a Mongoid Class. I'm not sure how I can do this with conditions?

    Here is an example:

    class Person
      include Mongoid::Document
    
      field :things, :type => Hash
    end
    

    So, let's say that I have this:

    p = Person.new
    p.things = {}
    p.things[:tv] = "Samsung"
    

    I want to query for the first person with a tv that is a Samsung...

    People.first(:conditions => ?????
    

    Thanks in advance.