Open In App

MongoDB – db.collection.CreateIndex() Method

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.

Syntax:



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

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:

For text indexes:

All these parameters are optional:

For 2dsphere Indexes:

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

For 2d Indexes:

All these parameters are optional:

For geoHaystack Indexes:

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

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 you are creating a wildcard index. It is an optional parameter.

Examples:

In the following examples, we are working with:

Database: gfg

Collections: student

Document: Three documents contains name and the language in which they are interested.

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

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

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

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

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

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

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

Here, we are creating 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.

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

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

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

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


Article Tags :