Open In App

MongoDB – db.collection.CreateIndex() Method

Last Updated : 10 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

MongoDB’s createIndex() method is used to create indexes on collections which allows for efficient querying and sorting of data. This method supports various types of indexes like text indexes, 2dsphere indexes, 2d indexes and more. It also provides options to customize the index creation process.

In this article, We will learn about the MongoDB createIndex() by understanding various options and examples in detail.

MongoDB createIndex()

  • MongoDB provides a createIndex() method to create one or more indexes on collections. Using this method we can create different types of indexes like text index, 2dsphere index, 2d index, etc.
  • It takes three parameters first one is a document that contains the field and value pairs where the field is the index key and the value describes the type of index for that field and others are optional.
  • If we are creating an index that is already present, then MongoDB does not recreate the existing index.
  • We can hide and unhide an index using the hideIndex() and unhideIndex() method.

Syntax:

db.Collection.name.createIndex(
    keys : {Field_name:1/-1},
    options : <document>,
    commitQuorum : <string or integer>
)

To learn more about optimizing MongoDB queries for full-stack applications, the Full Stack Development with Node JS course provides in-depth lessons on indexing and query optimization in MongoDB.

Parameters:

  • The first parameter is a document that contains the field and value pairs where the field is the index key and the value describes the type of index for that field. For an ascending index on a field, specify the value 1 and for descending index, specify the value -1.
  • Others are optional.

Optional Parameters:

  • Options: It is a set of options that controls the creation of the index. The type of this parameter is document.
  • commitQuorum: It is the minimum number of data-bearing voting replica set members.

Options

In createIndex() method, the options document contains a set of options that controls the creation of the index.

The following options are available for all the index types unless otherwise is specified and these options are optional:

  • background: The type of this parameter is boolean and the background: true directs MongoDB to build the index in the background. Background builds do not block operations on the collection. If you try to set the background option when creating an index in MongoDB, the database will ignore this setting.
  • unique: The type of this parameter is boolean and specify true to create a unique index. The default value is false. It creates a unique index so that the collection will not accept the insertion or update of documents where the index key value matches an existing value in the index.
  • name: It is the name of the index. The type of this parameter is string. If it is unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order.
  • partialFilterExpression: The type of this parameter is a document. If it is specified, the index only references documents that match the filter expression.
  • sparse: The type of this parameter is boolean. If it is true the index only references documents with the specified field. The default value is false.
  • expireAfterSeconds: The type of this parameter is an integer. It specifies a value, in seconds as a TTL to control how long MongoDB retains documents in this collection.
  • hidden: The type of this parameter is boolean. It is a flag that determines whether the index is hidden from the query planner or not. Because a hidden index is not evaluated as part of the query plan selection. The default value of this parameter is false.
  • storageEngine: The type of this parameter is a document. It allows users to configure the storage engine on a per-index basis when creating an index.

Some indexes may have additional options that are specified for that type only like:

1. Options For text indexes

All these parameters are optional:

  • weights: It is of document type and contains the field and weight pairs for text index. The default value for this parameter is 1.
  • default_language: It is of string type and specifies the language that determines the list of stop words and the rules for stemmer and tokenizer.
  • language_override: It is of string type and specifies the name of the fields in the document that contains the override language for the document.
  • textIndexVersion: It is of integer type and specifies the text index version number.

2. Options For 2dsphere Indexes

2dsphereIndexVersion: it is of integer type and specifies the 2dsphere index version number. It is an optional parameter.

3. Options For 2d Indexes

All these parameters are optional:

  • bits: It is of integer type and specifies the number of precision of the stored geohash value of the location data. The default value of this parameter is 26.
  • min: It is of number type and specifies the lower inclusive boundary for the longitude and latitude values. The default value of this parameter is -180.0.
  • max: It is of number type and specifies the higher inclusive boundary for the longitude and latitude values. The default value of this parameter is -180.0.

4. Options For geoHaystack Indexes

bucketSize: It is of number type and specifies the number of units within which to group the local valuesThis parameter must be set to a value greater than 0. 

5. Options For wildcard indexes

wildcardProjection: It is of document type and allows users to include or exclude specific field paths from the wildcard index. It is only valid if we are creating a wildcard index. It is an optional parameter.

Examples of MongoDB createIndex()

We will use the below student collection in this article to understand the MongoDB createIndex() as shown below:

Example 1: Create an Ascending Index on a Single Field

db.student.createIndex({name:1})

Output:

Here, we have created an ascending index on the single field (i.e., name) without options.

Example 2: Create a Descending Index on a Single Field

db.student.createIndex({language:-1})

Output:

Here, we have create a descending index on the single field (i.e., language).

Example 3: Create an Index on the Multiple Fields

 db.student.createIndex({name:1,language:-1})

Output:

Here, we have create index on the multiples fields(i.e., Ascending index on the name and Descending index on the language field) using createIndex() method.

Example 4: Creating a Unique Index Using Options:

db.student.createIndex({name:1},{unique:true})

Output:

Here, we have created a unique index so that the collection will not accept the insertion or update of documents where the index key value matches an existing value in the index.

Example 5: Creating a Wildcard Index

First of all, we insert one more document in the student collection that contains the branch field.

Output:

Now we create a wildcard index on a single field path:

db.student.createIndex({"branch.$**":1})

Output:

wildcard-index

Here, we have created a wildcard index on the branch field using createIndex() method.

Example 6: Create Indexes with Collation Specified

> db.student.createIndex( { "name": 1 }, { collation: { locale: "en", strength: 2 } } )

Output:

{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}

Explanation: In this example, we create an index on the “name” field with collation specified. The locale option specifies the language-specific rules for string comparison (here, “en” for English) and strength specifies the level of comparison (2 for case-insensitive comparison).

Example 7: Create Index With Commit Quorum

> db.student.createIndex( { "name": 1 }, { commitQuorum: "majority" } )

Output:

{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}

Explanation: Here, we create an index on the “name” field with commit quorum specified. The commitQuorum option ensures that the majority of replica set members acknowledge the index creation operation before returning success.

Conclusion

Using createIndex(), MongoDB users can create indexes customize to their specific needs, improving query performance and enabling advanced data retrieval operations. Understanding the options and parameters of this method is key to optimizing database performance.

FAQs on MongoDB createIndex()

Can I create multiple indexes on a single field using createIndex()?

Yes, it is possible to create multiple indexes on a single field, with each index having different options or types.

What will happen if I attempt to create an index that already exists?

MongoDB does not recreate an index that already exists. It will return immediately without making any changes.

Can I create an index with a TTL (Time-To-Live) to automatically expire documents?

Yes, you can use the expireAfterSeconds option to specify a TTL for documents in the collection. It will automatically delete documents after the defined time.

How can I verify if an index exists on a collection?

You can use the getIndexes() method on a collection to list all indexes and check if a specific index exists



Next Article

Similar Reads

three90RightbarBannerImg
  翻译: