MongoDB CreateIndex() Method (original) (raw)

Last Updated : 5 May, 2026

MongoDB’s createIndex() is used to create indexes on collection fields to improve query and sorting performance, with support for multiple index types and customization options.

Syntax

db.collectionName.createIndex(
{ field_name: 1 },
{
commitQuorum:
}
)

Common Index Options

The following options are available for all the index types unless otherwise 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 2d sphere 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: Number of units to group local values (must be > 0).

5. Options For wildcard indexes

**wildcardProjection: Includes or excludes specific field paths from wildcard indexing.

Examples of MongoDB createIndex()

Consider below student collection to understand the MongoDB createIndex() as shown below:

Screenshot-2026-02-18-102807

Example 1: Create an Ascending Index on a Single Field

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

**Output:

Screenshot-2026-02-18-103338

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:

Screenshot-2026-02-18-103432

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:

Screenshot-2026-02-18-103631

Example 4: Creating a Unique Index Using Options:

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

**Output:

Screenshot-2026-02-18-103856

Example 5: Creating a Wildcard Index

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

**Output:

Screenshot-2026-02-18-104834

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

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

**Output:

Screenshot-2026-02-18-105110

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:

Screenshot-2026-02-18-105327

Example 7: Create Index With Commit Quorum

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

**Output:

name_1

**Note: Before using commitQuorum, MongoDB must be running as a replica set (not standalone) and the replica set should be initialized; otherwise, the command will fail.