MongoDB db.collection.CreateIndex() Method (original) (raw)

**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()

**Syntax:

db.Collection.name.createIndex(
    keys : {Field_name:1/-1},
    options : ,
    commitQuorum :
)

**Parameters:

**Optional Parameters:

**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:

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

1. Options For text indexes

All these parameters are optional:

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:

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.