Compound Indexes
On this page
Overview
Compound indexes hold references to multiple fields within a collection's documents, improving query and sort performance.
When creating a compound index, you must specify the following details:
The fields on which to create the index
The sort order for each field (ascending or descending)
Sample Data
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.
Create a Compound Index
Use the create_one
method to create a compound index. The following
example creates an index in descending order on the runtime
field and
in ascending order on the year
field:
collection.indexes.create_one({ runtime: -1, year: 1 })
Verify Index Creation
You can verify that the index was created by listing the indexes in the
collection. You should see an index for runtime
and year
in the list,
as shown in the following output:
puts collection.indexes.collect(&:to_json)
{"v": 2, "key": {"runtime": -1, "year": 1}, "name": "runtime_-1_year_1"}
Example Query
The following is an example of a query that is covered by the index
created on the runtime
and year
fields:
filter = { '$and' => [ { runtime: { '$gt' => 90 } }, { year: { '$gt' => 2005 } } ] } doc = collection.find(filter).first if doc puts doc.to_json else puts "No document found" end
{"_id":...,"runtime": 91,...,"title": "Monster House",...,"year": 2006,...}
Additional Information
To view runnable examples that demonstrate how to manage indexes, see Optimize Queries by Using Indexes.
To learn more about compound indexes, see Compound Indexes in the MongoDB Server manual.
API Documentation
To learn more about any of the methods discussed in this guide, see the following API documentation: