MongoDB – db.collection.CreateIndex() Method

29 Jun, 2022
In MongoDB, indexes are special data structures that store some information related to the documents such that it becomes easy for MongoDB to find the right data file. The indexes are ordered by the value of the field specified in the index. So, 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 you are creating an index that is already present, then MongoDB does not recreate the existing index.
You can hide and unhide an index using hideIndex() and unhideIndex() method.
Syntax:
db.Collection.name.createIndex(
    keys : {Field_name:1/-1},
    options : <document>,
    commitQuorum : <string or integer>
)
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.
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. MongoDB ignores the background option if specified.
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:
All these parameters are optional:
weights: It is of document type and contains the field and weight pairs for text index. The default value of 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.
2dsphereIndexVersion: it is of integer type and specifies the 2dsphere index version number. It is an optional parameter.
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.
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. 
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.
Create an index without option: 
db.student.createIndex({name:1})
Here, we create an ascending index on the single field (i.e., name) without options.
Create a descending index on the single field language:
db.student.createIndex({language:-1})
Here, we create a descending index on the single field (i.e., language).
Create an index on the multiple fields:
 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.
Creating a unique index using options:
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.
Creating a wildcard index on a single field path:
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.
khushb99
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.