Coffee Bite
Coffee Bite

Reputation: 5164

How can I index a hash field in MongoDB or Mongoid?

I have the following mongo document:

{
  _id: 'someid',
  name: 'John Doe',
  address: {
    city: 'Osaka',
    country: 'Japan'
  }
}

How do I index by city and country?

Upvotes: 3

Views: 1243

Answers (1)

mu is too short
mu is too short

Reputation: 434935

From the MongoDB documentation:

Indexing on Embedded Fields

You can create indexes on fields embedded in sub-documents, just as you can index top-level fields in documents. [...] Instead, indexes on embedded fields allow you to use a “dot notation,” to introspect into sub-documents.

[...]

db.people.ensureIndex( { "address.zipcode": 1 } )

Mongoid uses the same Dot Notation:

You can define indexes on embedded document fields as well.

class Person
  include Mongoid::Document
  embeds_many :addresses
  index "addresses.street"
end

So you want something like this:

class C
  include Mongoid::Document
  index 'address.city'
  index 'address.country'
  #...
end

Upvotes: 5

Related Questions