MongoDB Method: db.collection.createIndex()

Summary

Method Namedb.collection.createIndex()
UsageCreate single index
Group index

Signature

db.collection.createIndex(keys, options, commitQuorum)

Usage

Create an index on a collection. We can set index based on fields, and also can set index with specific name.

NOTES

  • If we try to recreate an existing index, then MongoDB ignores that command and does not create it.
  • Use rolling index build while creating an index on a replica set or shared cluster.

Arguments

ParameterDescriptionTypeOptional
keysKeys for setting indexdocument
optionsSome special options for the updatedocumentyes
commitQuorumMinimum number of voting replica setinteger or stringyes

“options” argument parameters

“options” argument accepts a document, an the following options are allowed in the document.

ParameterDescriptionTypeDefaultOptional
uniqueCreate a uniquebooleanfalseyes
nameName of the indexdocumentyes
partialFilterExpressionOnly consider documents that matches the filterdocumentyes
sparseRefer to documents with specific fieldbooleanfalseyes
expireAfterSecondsExpire time in secondsintegeryes
hiddenDefine hidden indexbooleanfalseyes
storageEngineSpecifiy storage engine for this specific indexdocumentyes

NOTES

  • Hidden indexes are not evaluated during query planning.

Return Value

Return valueCase for the return value
deleteCountNumber of document
acknowledgedtrue if writeConcert is provided, or false otherwise

NOTES

  • for this deleteOne() method, the value of deleteCount will be one of the following
    • 1 => if the filter matches one or more document and one document was deleted
    • 0 => if the filter does not match any existing document

Examples

Here are a few examples of the method usage-

# MongoDB db.collection.createIndex() method demo

# Create unique index
# email => ascending
bigboxcode> db.customer.createIndex({email: 1}, {unique: true})

output:
email_1


# Check indexes
bigboxcode> db.customer.getIndexes()

output:
[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { email: 1 }, name: 'email_1', unique: true }
]


# Set index with name
# name => ascending
bigboxcode> db.customer.createIndex({name: 1}, {name: "my_name_idx"})

output:
my_name_idx

# Check indexes
bigboxcode> db.customer.getIndexes()

output:
[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { email: 1 }, name: 'email_1', unique: true },
  { v: 2, key: { name: 1 }, name: 'my_name_idx' }
]

# Set index
# address.country => ascending
# address.state => ascending
# address.zipcode => hashed
bigboxcode> db.customer.createIndex({"address.country": 1, "address.state" : 1, "address.zipcode" : "hashed"})

output:
address.country_1_address.state_1_address.zipcode_hashed

# Check indexes
bigboxcode> db.customer.getIndexes()

output:
[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { email: 1 }, name: 'email_1', unique: true },
  { v: 2, key: { name: 1 }, name: 'my_name_idx' },
  {
    v: 2,
    key: {
      'address.country': 1,
      'address.state': 1,
      'address.zipcode': 'hashed'
    },
    name: 'address.country_1_address.state_1_address.zipcode_hashed'
  }
]


# Insert some documents
bigboxcode> db.customer.insertMany([
  {
    "name": "Izabella Conroy",
    "email": "izabella.conroy@hotmail.com",
    "age": 19,
    "phone": "108-679-2154",
    "address": {
      "street": "11 North Vineyard Drive",
      "city": "Minneapolis",
      "state": "Minnesota",
      "postalCode": "19426",
      "country": "US"
    },
    "profileCompletenessScore": 30
  },
  {
    "name": "Lambert Purdy",
    "email": "lambert@gmail.com",
    "age": 28,
    "phone": "(610) 489-3633",
    "address": {
      "street": "305 2nd Ave",
      "city": "Collegeville",
      "state": "Minnesota",
      "postalCode": "81007",
      "country": "US"
    },
    "profileCompletenessScore": 40
  },
  {
    "name": "Alisa Parker",
    "email": "alisa@example.com",
    "age": 72,
    "phone": "768-319-1054",
    "address": {
      "street": "8532 Ingalls Circle",
      "city": "Arvada",
      "state": "CO",
      "postalCode": "80003",
      "country": "CA"
    },
    "profileCompletenessScore": 60
  },
  {
    "name": "Eloise Weber",
    "email": "weber@example.com",
    "age": 29,
    "phone": "618-357-2104",
    "address": {
      "street": "632 Belmar Drive",
      "city": "Edmond",
      "state": "OK",
      "postalCode": "73025",
      "country": "CA"
    },
    "profileCompletenessScore": 80
  }
])

output:
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId('65ed9fb6c48992542d0273e4'),
    '1': ObjectId('65ed9fb6c48992542d0273e5'),
    '2': ObjectId('65ed9fb6c48992542d0273e6'),
    '3': ObjectId('65ed9fb6c48992542d0273e7')
  }
}

# Expalain find query
bigboxcode> db.customer.find({"email": "lambert@gmail.com"}).explain()

output:
{
  explainVersion: '2',
  queryPlanner: {
    namespace: 'bigboxcode.customer',
    indexFilterSet: false,
    parsedQuery: { email: { '$eq': 'lambert@gmail.com' } },
    queryHash: 'B9CE814D',
    planCacheKey: 'F305ACEB',
    maxIndexedOrSolutionsReached: false,
    maxIndexedAndSolutionsReached: false,
    maxScansToExplodeReached: false,
    winningPlan: {
      queryPlan: {
        stage: 'FETCH',
        planNodeId: 2,
        inputStage: {
          stage: 'IXSCAN',
          planNodeId: 1,
          keyPattern: { email: 1 },
          indexName: 'email_1',
          isMultiKey: false,
          multiKeyPaths: { email: [] },
          isUnique: true,
          isSparse: false,
          isPartial: false,
          indexVersion: 2,
          direction: 'forward',
          indexBounds: { email: [ '["lambert@gmail.com", "lambert@gmail.com"]' ] }
        }
      },
      slotBasedPlan: {
        slots: '$$RESULT=s11 env: { s1 = TimeZoneDatabase(Africa/Lagos...America/Atikokan) (timeZoneDB), s10 = {"email" : 1}, s2 = Nothing (SEARCH_META), s5 = KS(3C6C616D6265727440676D61696C2E636F6D000104), s3 = 1710072329812 (NOW), s6 = KS(3C6C616D6265727440676D61696C2E636F6D00FE04) }',
        stages: '[2] nlj inner [] [s4, s7, s8, s9, s10] n' +
          '    left n' +
          '        [1] cfilter {(exists(s5) && exists(s6))} n' +
          '        [1] ixseek s5 s6 s9 s4 s7 s8 [] @"ab70d0c8-768d-4727-ba98-bcddf07b3a0e" @"email_1" true n' +
          '    right n' +
          '        [2] limit 1 n' +
          '        [2] seek s4 s11 s12 s7 s8 s9 s10 [] @"ab70d0c8-768d-4727-ba98-bcddf07b3a0e" true false n'
      }
    },
    rejectedPlans: []
  },
  command: {
    find: 'customer',
    filter: { email: 'lambert@gmail.com' },
    '$db': 'bigboxcode'
  },
  serverInfo: {
    host: 'f50c92e32d6b',
    port: 27017,
    version: '7.0.4',
    gitVersion: '38f3e37057a43d2e9f41a39142681a76062d582e'
  },
  serverParameters: {
    internalQueryFacetBufferSizeBytes: 104857600,
    internalQueryFacetMaxOutputDocSizeBytes: 104857600,
    internalLookupStageIntermediateDocumentMaxSizeBytes: 104857600,
    internalDocumentSourceGroupMaxMemoryBytes: 104857600,
    internalQueryMaxBlockingSortMemoryUsageBytes: 104857600,
    internalQueryProhibitBlockingMergeOnMongoS: 0,
    internalQueryMaxAddToSetBytes: 104857600,
    internalDocumentSourceSetWindowFieldsMaxMemoryBytes: 104857600,
    internalQueryFrameworkControl: 'trySbeEngine'
  },
  ok: 1
}


# Expain a find query and checke used index
bigboxcode> db.customer.find({"address.country": "US"}).explain()

output:
{
  explainVersion: '2',
  queryPlanner: {
    namespace: 'bigboxcode.customer',
    indexFilterSet: false,
    parsedQuery: { 'address.country': { '$eq': 'US' } },
    queryHash: '7F4E5F2D',
    planCacheKey: '7FA5F99E',
    maxIndexedOrSolutionsReached: false,
    maxIndexedAndSolutionsReached: false,
    maxScansToExplodeReached: false,
    winningPlan: {
      queryPlan: {
        stage: 'FETCH',
        planNodeId: 2,
        inputStage: {
          stage: 'IXSCAN',
          planNodeId: 1,
          keyPattern: {
            'address.country': 1,
            'address.state': 1,
            'address.zipcode': 'hashed'
          },
          indexName: 'address.country_1_address.state_1_address.zipcode_hashed',
          isMultiKey: false,
          isUnique: false,
          isSparse: false,
          isPartial: false,
          indexVersion: 2,
          direction: 'forward',
          indexBounds: {
            'address.country': [ '["US", "US"]' ],
            'address.state': [ '[MinKey, MaxKey]' ],
            'address.zipcode': [ '[MinKey, MaxKey]' ]
          }
        }
      },
      slotBasedPlan: {
        slots: '$$RESULT=s11 env: { s1 = TimeZoneDatabase(Africa/Lagos...America/Atikokan) (timeZoneDB), s10 = {"address.country" : 1, "address.state" : 1, "address.zipcode" : "hashed"}, s2 = Nothing (SEARCH_META), s5 = KS(3C5553000A0A0104), s3 = 1710072246189 (NOW), s6 = KS(3C555300F0F0FE04) }',
        stages: '[2] nlj inner [] [s4, s7, s8, s9, s10] n' +
          '    left n' +
          '        [1] cfilter {(exists(s5) && exists(s6))} n' +
          '        [1] ixseek s5 s6 s9 s4 s7 s8 [] @"ab70d0c8-768d-4727-ba98-bcddf07b3a0e" @"address.country_1_address.state_1_address.zipcode_hashed" true n' +
          '    right n' +
          '        [2] limit 1 n' +
          '        [2] seek s4 s11 s12 s7 s8 s9 s10 [] @"ab70d0c8-768d-4727-ba98-bcddf07b3a0e" true false n'
      }
    },
    rejectedPlans: []
  },
  command: {
    find: 'customer',
    filter: { 'address.country': 'US' },
    '$db': 'bigboxcode'
  },
  serverInfo: {
    host: 'f50c92e32d6b',
    port: 27017,
    version: '7.0.4',
    gitVersion: '38f3e37057a43d2e9f41a39142681a76062d582e'
  },
  serverParameters: {
    internalQueryFacetBufferSizeBytes: 104857600,
    internalQueryFacetMaxOutputDocSizeBytes: 104857600,
    internalLookupStageIntermediateDocumentMaxSizeBytes: 104857600,
    internalDocumentSourceGroupMaxMemoryBytes: 104857600,
    internalQueryMaxBlockingSortMemoryUsageBytes: 104857600,
    internalQueryProhibitBlockingMergeOnMongoS: 0,
    internalQueryMaxAddToSetBytes: 104857600,
    internalDocumentSourceSetWindowFieldsMaxMemoryBytes: 104857600,
    internalQueryFrameworkControl: 'trySbeEngine'
  },
  ok: 1
}


# Check expalin output when there is no index
bigboxcode> db.customer.find({profileCompletenessScore: {$gt: 50}}).explain()

output:
{
  explainVersion: '2',
  queryPlanner: {
    namespace: 'bigboxcode.customer',
    indexFilterSet: false,
    parsedQuery: { profileCompletenessScore: { '$gt': 50 } },
    queryHash: '641EB697',
    planCacheKey: '85D689DF',
    maxIndexedOrSolutionsReached: false,
    maxIndexedAndSolutionsReached: false,
    maxScansToExplodeReached: false,
    winningPlan: {
      queryPlan: {
        stage: 'COLLSCAN',
        planNodeId: 1,
        filter: { profileCompletenessScore: { '$gt': 50 } },
        direction: 'forward'
      },
      slotBasedPlan: {
        slots: '$$RESULT=s5 env: { s1 = TimeZoneDatabase(Africa/Lagos...America/Atikokan) (timeZoneDB), s7 = 50, s2 = Nothing (SEARCH_META), s3 = 1710072480130 (NOW) }',
        stages: '[1] filter {traverseF(s4, lambda(l1.0) { ((l1.0 > s7) ?: false) }, false)} n' +
          '[1] scan s5 s6 none none none none lowPriority [s4 = profileCompletenessScore] @"ab70d0c8-768d-4727-ba98-bcddf07b3a0e" true false '
      }
    },
    rejectedPlans: []
  },
  command: {
    find: 'customer',
    filter: { profileCompletenessScore: { '$gt': 50 } },
    '$db': 'bigboxcode'
  },
  serverInfo: {
    host: 'f50c92e32d6b',
    port: 27017,
    version: '7.0.4',
    gitVersion: '38f3e37057a43d2e9f41a39142681a76062d582e'
  },
  serverParameters: {
    internalQueryFacetBufferSizeBytes: 104857600,
    internalQueryFacetMaxOutputDocSizeBytes: 104857600,
    internalLookupStageIntermediateDocumentMaxSizeBytes: 104857600,
    internalDocumentSourceGroupMaxMemoryBytes: 104857600,
    internalQueryMaxBlockingSortMemoryUsageBytes: 104857600,
    internalQueryProhibitBlockingMergeOnMongoS: 0,
    internalQueryMaxAddToSetBytes: 104857600,
    internalDocumentSourceSetWindowFieldsMaxMemoryBytes: 104857600,
    internalQueryFrameworkControl: 'trySbeEngine'
  },
  ok: 1
}

Code Implementations

Here are the usage examples of the MongoDB method in Golang, NodeJS, Java, Python programming languages.

// MongoDB db.collection.createIndex() method examples in Golang

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	_ "go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const uri = "mongodb://bigboxuser:bigboxpass@localhost:27017/?maxPoolSize=20&w=majority"

func main() {
	// Initiate mongo client
	mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
	if err != nil {
		fmt.Println("MongoDB connection error: ", err)
		os.Exit(1)
	}
	defer mongoClient.Disconnect(context.Background())

	// Initiate collection instance
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	customerCollection := mongoClient.Database("bigboxcode").Collection("customer")

	// Create unique index
	// email => ascending
	// bigboxcode> db.customer.createIndex({email: 1}, {unique: true})
	createIndexResult, err := customerCollection.Indexes().CreateOne(ctx, mongo.IndexModel{
		Keys:    bson.D{{"email", 1}},
		Options: options.Index().SetUnique(true),
	})

	if err != nil {
		fmt.Println("Command: db.customer.createIndex({email: 1}, {unique: true}) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.createIndex({email: 1}, {unique: true}) | Result: ", createIndexResult)

	// Set index with name
	// name => ascending
	createIndexResult, err = customerCollection.Indexes().CreateOne(
		context.Background(),
		mongo.IndexModel{
			Keys:    bson.D{{"name", 1}},
			Options: options.Index().SetName("my_name_idx"),
		},
	)

	if err != nil {
		fmt.Println("Command: db.customer.createIndex({name: 1}, {name: "my_name_idx"}) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.createIndex({name: 1}, {name: "my_name_idx"}) | Result: ", createIndexResult)

	// Set index
	// address.country => ascending
	// address.state => ascending
	// address.zipcode => hashed
	createIndexResult, err = customerCollection.Indexes().CreateOne(
		context.Background(),
		mongo.IndexModel{
			Keys: bson.D{
				{"address.country", 1},
				{"address.state", 1},
				{"address.zipcode", "hashed"},
			},
		},
	)

	if err != nil {
		fmt.Println("Command: db.customer.createIndex({"address.country": 1, "address.state" : 1, "address.zipcode" : "hashed"}) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.createIndex({"address.country": 1, "address.state" : 1, "address.zipcode" : "hashed"}) | Result: ", createIndexResult)

}

Output:

Command: db.customer.createIndex({email: 1}, {unique: true}) | Result:  email_1

Command: db.customer.createIndex({name: 1}, {name: "my_name_idx"}) | Result:  my_name_idx

Command: db.customer.createIndex({"address.country": 1, "address.state" : 1, "address.zipcode" : "hashed"}) | Result:  address.country_1_address.state_1_address.zipcode_hashed

NOTES

  • Use the “Index().CreateOne()” method from “mongo-go-driver
  • Signature of the method-
    • func (iv IndexView) CreateOne(ctx context.Context, model IndexModel, opts ...*options.CreateIndexesOptions) (string, error)
  • Definition of IndexModel

    type IndexModel struct {
        Keys interface{}
        Options *options.IndexOptions
    }
  • Definition of CreateIndexOptions

    type CreateIndexesOptions struct {
        CommitQuorum interface{}
        MaxTime *time.Duration
    }
// db.collection.createIndex() method example in NodeJS

import { MongoClient } from "mongodb";

async function main() {
  // Define MongoDB connection URI
  const uri = "mongodb://bigboxuser:bigboxpass@127.0.0.1:27017";

  // Create a client
  const mongo = new MongoClient(uri);

  try {
    await mongo.connect();

    const database = mongo.db("bigboxcode");
    const customerCollection = database.collection("customer");

    // Create unique index on email field
    let commandResult = await customerCollection.createIndex(
      { email: 1 },
      { unique: true }
    );

    console.log(
      "Command: db.customer.createIndex({email: 1}, {unique: true}) | Result:",
      commandResult
    );

    // Check indexes
    commandResult = await customerCollection.indexes();

    console.log("Command: db.customer.getIndexes() | Result:", commandResult);

    // Set index with name
    commandResult = await customerCollection.createIndex(
      { name: 1 },
      { name: "my_name_idx" }
    );

    console.log(
      'Command: db.customer.createIndex({name: 1}, {name: "my_name_idx"}) | Result: ',
      commandResult
    );

    // Check indexes
    commandResult = await customerCollection.indexes();
    console.log("Command: db.customer.getIndexes() | Result:", commandResult);

    // Set compound index on address fields with hashed zipcode
    await customerCollection.createIndex(
      { "address.country": 1, "address.state": 1, "address.zipcode": "hashed" },
      { name: "address.country_1_address.state_1_address.zipcode_hashed" }
    );

    console.log(
      'Command: Command: db.customer.createIndex({"address.country": 1, "address.state" : 1, "address.zipcode" : "hashed"}) | Result: ',
      commandResult
    );

    // Check indexes
    commandResult = await customerCollection.indexes();
    console.log("Command: db.customer.getIndexes() | Result:", commandResult);
  } finally {
    await mongo.close();
  }
}

await main().catch(console.error);

process.exit(0);

Output:

Command: db.customer.createIndex({email: 1}, {unique: true}) | Result: email_1
Command: db.customer.getIndexes() | Result: [
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { email: 1 }, name: 'email_1', unique: true }
]
Command: db.customer.createIndex({name: 1}, {name: "my_name_idx"}) | Result:  my_name_idx
Command: db.customer.getIndexes() | Result: [
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { email: 1 }, name: 'email_1', unique: true },
  { v: 2, key: { name: 1 }, name: 'my_name_idx' }
]
Command: Command: db.customer.createIndex({"address.country": 1, "address.state" : 1, "address.zipcode" : "hashed"}) | Result:  [
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { email: 1 }, name: 'email_1', unique: true },
  { v: 2, key: { name: 1 }, name: 'my_name_idx' }
]
Command: db.customer.getIndexes() | Result: [
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { email: 1 }, name: 'email_1', unique: true },
  { v: 2, key: { name: 1 }, name: 'my_name_idx' },
  {
    v: 2,
    key: {
      'address.country': 1,
      'address.state': 1,
      'address.zipcode': 'hashed'
    },
    name: 'address.country_1_address.state_1_address.zipcode_hashed'
  }
]

NOTES

  • Use NodeJS “createIndex()” method from the package “mongodb“.
  • Method signatures are-
    • createIndex(indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise<string>
# db.collection.createIndex() method example in Python

from pymongo import MongoClient, WriteConcern
import re
from datetime import datetime

# Create MongoDB client
mongo_client = MongoClient("mongodb://bigboxuser:bigboxpass@127.0.0.1:27017/")

# Select database and collection
mongo_database = mongo_client.bigboxcode
customer_collection = mongo_database.customer

try:
    # Create unique index on email field
    command_result = customer_collection.create_index([("email", 1)], unique=True)

    print(
        "Command: db.customer.createIndex({email: 1}, {unique: true}) | Result:",
        command_result,
    )

    # Check indexes
    command_result = customer_collection.index_information()
    print("Indexes:", command_result)

    # Set index with name
    command_result = customer_collection.create_index([("name", 1)], name="my_name_idx")

    print(
        'Command: db.customer.createIndex({name: 1}, {name: "my_name_idx"}) | Result:',
        command_result,
    )

    # Check indexes
    command_result = customer_collection.index_information()
    print("Indexes:", command_result)

    # Set compound index on address fields with hashed zipcode
    command_result = customer_collection.create_index(
        [("address.country", 1), ("address.state", 1), ("address.zipcode", "hashed")],
        name="address.country_1_address.state_1_address.zipcode_hashed",
    )

    print(
        'Command: Command: db.customer.createIndex({"address.country": 1, "address.state" : 1, "address.zipcode" : "hashed"}) | Result:',
        command_result,
    )

    # Check indexes
    command_result = customer_collection.index_information()
    print("Indexes:", command_result)
finally:
    mongo_client.close()

Output:

Command: db.customer.createIndex({email: 1}, {unique: true}) | Result: email_1

Indexes: {'_id_': {'v': 2, 'key': [('_id', 1)]}, 'email_1': {'v': 2, 'key': [('email', 1)], 'unique': True}}

Command: db.customer.createIndex({name: 1}, {name: "my_name_idx"}) | Result: my_name_idx

Indexes: {'_id_': {'v': 2, 'key': [('_id', 1)]}, 'email_1': {'v': 2, 'key': [('email', 1)], 'unique': True}, 'my_name_idx': {'v': 2, 'key': [('name', 1)]}}

Command: Command: db.customer.createIndex({"address.country": 1, "address.state" : 1, "address.zipcode" : "hashed"}) | Result: address.country_1_address.state_1_address.zipcode_hashed

Indexes: {'_id_': {'v': 2, 'key': [('_id', 1)]}, 'email_1': {'v': 2, 'key': [('email', 1)], 'unique': True}, 'my_name_idx': {'v': 2, 'key': [('name', 1)]}, 'address.country_1_address.state_1_address.zipcode_hashed': {'v': 2, 'key': [('address.country', 1), ('address.state', 1), ('address.zipcode', 'hashed')]}}

NOTES

  • Use method “create_index” from redis-py.
  • Signature of the method is –
    • def create_index(
              self,
              keys: _IndexKeyHint,
              session: Optional[ClientSession] = None,
              comment: Optional[Any] = None,
              **kwargs: Any,
          ) -> str
// db.collection.createIndex() method example in Java

import com.mongodb.client.*;
import com.mongodb.client.model.IndexOptions;
import org.bson.Document;

public class CreateIndex {
    public static void main(String[] args) {
        String uri = "mongodb://bigboxuser:bigboxpass@localhost:27017/";

        try (MongoClient mongoClient = MongoClients.create(uri)) {
            MongoDatabase database = mongoClient.getDatabase("bigboxcode");
            MongoCollection<Document> customerCollection = database.getCollection("customer");

            // Create unique index on email field
            customerCollection.createIndex(new Document("email", 1), new IndexOptions().unique(true));

            // Check indexes
            System.out.println("Indexes:");
            for (Document index : customerCollection.listIndexes()) {
                System.out.println(index.toJson());
            }

            // Set index with name
            customerCollection.createIndex(new Document("name", 1), new IndexOptions().name("my_name_idx"));

            // Check indexes
            System.out.println("Indexes:");
            for (Document index : customerCollection.listIndexes()) {
                System.out.println(index.toJson());
            }

            // Set compound index on address fields with hashed zipcode
            customerCollection.createIndex(
                    new Document("address.country", 1)
                            .append("address.state", 1)
                            .append("address.zipcode", "hashed")
            );

            // Check indexes
            System.out.println("Indexes:");
            for (Document index : customerCollection.listIndexes()) {
                System.out.println(index.toJson());
            }
            mongoClient.close();

        }
    }
}

Output:

Indexes:
{"v": 2, "key": {"_id": 1}, "name": "_id_"}
{"v": 2, "key": {"email": 1}, "name": "email_1", "unique": true}

Indexes:
{"v": 2, "key": {"_id": 1}, "name": "_id_"}
{"v": 2, "key": {"email": 1}, "name": "email_1", "unique": true}
{"v": 2, "key": {"name": 1}, "name": "my_name_idx"}

Indexes:
{"v": 2, "key": {"_id": 1}, "name": "_id_"}
{"v": 2, "key": {"email": 1}, "name": "email_1", "unique": true}
{"v": 2, "key": {"name": 1}, "name": "my_name_idx"}
{"v": 2, "key": {"address.country": 1, "address.state": 1, "address.zipcode": "hashed"}, "name": "address.country_1_address.state_1_address.zipcode_hashed"}

NOTES

  • Use the method “createIndex()” from MongoCollection.
  • Signatures of the method are-
    • String createIndex(Bson keys)
    • String createIndex(Bson keys, IndexOptions indexOptions)
    • String createIndex(ClientSession clientSession, Bson keys)
    • String createIndex(ClientSession clientSession, Bson keys, IndexOptions indexOptions)

Source Code

Use the following links to get the source code used in this article-

Related Methods

CommandDetails
db.collection.getIndexes() Method Details

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.