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
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.
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 single field index. The following example creates an index in ascending order on the title
field:
collection.indexes.create_one({ title: 1 })
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:
puts collection.indexes.collect(&:to_json)
{"v": 2, "key": {"title": 1}, "name": "title_1"}
The following is an example of a query that is covered by the index created on the title
field:
filter = { title: 'Sweethearts' }doc = collection.find(filter).firstif doc puts doc.to_jsonelse puts "No document found"end
{"_id":...,"plot":"A musical comedy duo...","genres":["Musical"],...,"title":"Sweethearts",...}
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.
To learn more about any of the methods discussed in this guide, see the following API documentation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4