Docs Menu
Docs Home
/ / /
Ruby MongoDB Driver
/

Multikey Indexes

On this page

  • Overview
  • Sample Data
  • Create a Multikey Index
  • Verify Index Creation
  • Example Query
  • Additional Information
  • API Documentation

Multikey indexes are indexes that improve the performance of queries on array-valued fields. You can create a multikey index on a collection by using the create_one method and the same syntax that you use to create a single field index.

When creating a multikey index, you must specify the following details:

  • The fields on which to create the index

  • The sort order for each field (ascending or descending)

The examples in this guide use the movies collection in the sample_mflix database from the Atlas sample datasets. To access this collection from your Ruby application, create a Mongo::Client object that connects to an Atlas cluster and assign the following values to your database and collection variables:

database = client.use('sample_mflix')
collection = database[:movies]

To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.

Use the create_one method to create a multikey index. The following example creates an index in ascending order on the cast field:

collection.indexes.create_one({ cast: 1 })

You can verify that the index was created by listing the indexes in the collection. You should see an index for cast in the list, as shown in the following output:

puts collection.indexes.collect(&:to_json)
{"v": 2, "key": {"cast": 1}, "name": "cast_1"}

The following is an example of a query that is covered by the index created on the cast field:

filter = { cast: { '$all' => ['Aamir Khan', 'Kajol'] } }
doc = collection.find(filter).first
if doc
puts doc.to_json
else
puts "No document found"
end
{"_id":...,"title":"Fanaa",...,"cast": ["Aamir Khan", "Kajol", "Rishi Kapoor", "Tabu"],...}

To view runnable examples that demonstrate how to manage indexes, see Optimize Queries by Using Indexes.

To learn more about multikey indexes, see Multikey Indexes in the MongoDB Server manual.

To learn more about any of the methods discussed in this guide, see the following API documentation:

Back

Compound