Docs Menu

Optimize Queries by Using Indexes

On this page, you can see copyable code examples that show how to manage different types of indexes by using the MongoDB Ruby Driver.

To use an example from this page, copy the code example into the sample application or your own application. Be sure to replace all placeholders in the code examples, such as <connection string>, with the relevant values for your MongoDB deployment.

You can use the following sample application to test the code on this page. To use the sample application, perform the following steps:

  1. Ensure you have the Ruby driver installed in your project. See the Download and Install guide to learn more.

  2. Copy the following code and paste it into a new .rb file.

  3. Copy a code example from this page and paste it on the specified lines in the file.

require 'mongo'
# Replace the placeholders with your credentials
uri = "<connection string>"
# Sets the server_api field of the options object to Stable API version 1
options = { server_api: { version: "1" }}
# Creates a new client and connect to the server
client = Mongo::Client.new(uri, options)
database = client.use('<database name>')
collection = database[:<collection name>]
# Start example code here
# End example code here
client.close

The following example creates an ascending index on the specified field:

collection.indexes.create_one({ <field name>: 1 })

To learn more about single field indexes, see the Single Field Indexes guide.

The following example creates a compound index on the two specified fields.

collection.indexes.create_one({ <field name 1>: -1, <field name 2>: 1 })

To learn more about compound indexes, see the Compound Indexes guide.

The following example creates a multikey index on the specified array-valued field:

collection.indexes.create_one({ <field name>: 1 })

To learn more about multikey indexes, see the Multikey Indexes guide.

The following example creates a 2dsphere index on the specified field that contains GeoJSON objects:

collection.indexes.create_one({ <GeoJSON field name>: '2dsphere' })

To learn more about geospatial indexes, see the Geospatial Indexes guide.

The following sections contain code examples that describe how to manage Atlas Search indexes.

To learn more about search indexes, see the Atlas Search Indexes guide.

The following example creates an Atlas Search index on the specified field:

index_definition = {
mappings: {
dynamic: false,
fields: {
<field name>: { type: '<field type>' }
}
}
}
collection.search_indexes.create_one(index_definition, name: '<index name>')

The following example prints a list of Atlas Search indexes in the specified collection:

puts collection.search_indexes.collect(&:to_json)

The following example updates an existing Atlas Search index with the specified new index definition:

updated_definition = {
mappings: {
dynamic: false,
fields: { <updated field name>: { type: '<updated field type>' } }
}
}
collection.search_indexes.update_one(updated_definition, name: '<index name>')

The following example deletes an Atlas Search index with the specified name:

collection.search_indexes.drop_one(name: '<index name>')

The following example creates a text index on the specified string field:

collection.indexes.create_one({ <field name>: 'text' })

To learn more about text indexes, see the Text Indexes guide.

The following example creates multiple indexes on the given array of index specifications:

collection.indexes.create_many([
{ key: { <field name 1>: 1 } },
{ key: { <field name 2>: -1 } },
])

The following example deletes an index with the specified name:

collection.indexes.drop_one( '<index name>' )

The following example shows how to delete all indexes in a collection:

collection.indexes.drop_all

The following example prints a list of all indexes in the specified collection:

puts collection.indexes.collect(&:to_json)

The following is a full list of the available options you can add when creating indexes. These options mirror the options supported by the createIndex command. For more information, see the createIndex command in the MongoDB Server manual.

Option
Description

:background

Either true or false. Tells the index to be created in the background.

:expire_after

Number of seconds to expire documents in the collection after.

:name

The name of the index.

:sparse

Whether the index should be sparse or not, either true or false.

:storage_engine

The name of the storage engine for this particular index.

:version

The index format version to use.

:default_language

The default language of text indexes.

:language_override

The field name to use when overriding the default language.

:text_version

The version format for text index storage.

:weights

A document specifying fields and weights in text search.

:sphere_version

The 2d sphere index version.

:bits

Sets the maximum boundary for latitude and longitude in the 2d index.

:max

Maximum boundary for latitude and longitude in the 2d index.

:min

Minimum boundary for latitude and longitude in the 2d index.

:bucket_size

The number of units within which to group the location values in a geo haystack index.

:partial_filter_expression

A filter for a partial index.

:hidden

A Boolean specifying whether the index should be hidden; a hidden index is one that exists on the collection but will not be used by the query planner.

:commit-quorum

Specify how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. Potential values are:

  • integer from 0 to the number of members of the replica set

  • “majority” indicating that a majority of data bearing nodes must vote

  • “votingMembers” which means that all voting data bearing nodes must vote

For more information, see commitQuorom in the MongoDB Server manual.

To learn more about the methods or objects used in this guide, see the following API documentation: