Overview
Single field indexes are indexes with a reference to a single field of a document in a collection. These indexes improve single field query and sort performance. They also support TTL Indexes that automatically remove documents from a collection after a certain amount of time or at a specified clock time.
When creating a single field index, you must specify the following details:
The field on which to create the index
The sort order for the indexed values as either ascending or descending
Note
The default _id_
index is an example of a single field index. This index is automatically created on the _id
field when a new collection is created.
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 Single Field Index
Use the create_one
method to create a single field index. The following example creates an index in ascending order on the title
field:
# Creates an index on the "title" field collection.indexes.create_one({ title: 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 title
in the list, as shown in the following output:
# Lists all indexes on the collection puts collection.indexes.collect(&:to_json)
{"v": 2, "key": {"title": 1}, "name": "title_1"}
Example Query
The following is an example of a query that is covered by the index created on the title
field:
# Finds a document with the title "Sweethearts" by using the newly created index filter = { title: 'Sweethearts' } doc = collection.find(filter).first if doc puts doc.to_json else puts "No document found" end
{"_id":...,"plot":"A musical comedy duo...", "genres":["Musical"],...,"title":"Sweethearts",...}
Additional Information
To view runnable examples that demonstrate how to manage indexes, see Optimize Queries by Using Indexes.
To learn more about single field indexes, see Single Field 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: