MongoDB Method: db.collection.getIndexes()

Summary

Method Namedb.collection.getIndexes()
UsageGet indexes of a collection
Group index

Signature

db.collection.getIndexes()

Usage

Get full information on all existing indexes of a collection.

NOTES

  • Hidden indexes are also included in the result of this method.

Arguments

There are no arguments for this method.

Return Value

Return valueCase for the return valueType
resultList of all indexes for that collectionarray[object]

NOTES

  • The output will like below-

    [
    { v: 2, key: { id: 1 }, name: '_id' },
    { v: 2, key: { some_field: field_sorting_order }, name: 'index_name' },
    ... some other indexes....
    ]

Examples

Here are a few examples of the method usage-

# MongoDB db.collection.getIndexes() method demo

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

output:
email_1

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

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

# Create hidden index
bigboxcode> db.customer.createIndex({profileCompletenessScore: 1}, {hidden: true})

output:
profileCompletenessScore_1


# Check the indexess of customer collection
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'
  },
  {
    v: 2,
    key: { profileCompletenessScore: 1 },
    name: 'profileCompletenessScore_1',
    hidden: true
  }
]

Code Implementations

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

// MongoDB db.collection.getIndexes() 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(
		ctx,
		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(
		ctx,
		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)

	// Set hidden index
	createIndexResult, err = customerCollection.Indexes().CreateOne(
		ctx,
		mongo.IndexModel{
			Keys:    bson.D{{"profileCompletenessScore", 1}},
			Options: options.Index().SetHidden(true),
		},
	)

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

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

	// Check indexes
	getIndexResult, err := customerCollection.Indexes().List(ctx)

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

	fmt.Println("Command: db.customer.getIndexes() | Result: ")

	for getIndexResult.Next(ctx) {
		var index bson.M
		err := getIndexResult.Decode(&index)

		if err != nil {
			fmt.Println(err)
		}

		fmt.Println(index)
	}

}

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

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

NOTES

  • Use the “Index().List()” method from “mongo-go-driver
  • Signature of the method-
    • func (iv IndexView) List(ctx context.Context, opts ...*options.ListIndexesOptions) (*Cursor, error)
  • Definition of ListIndexOptions

    type ListIndexesOptions struct {
        BatchSize *int32
        MaxTime *time.Duration
    }
  • Definition of Cursor struct-

    type Cursor struct {
        Current bson.Raw
        bc            batchCursor
        batch         *bsoncore.DocumentSequence
        batchLength   int
        bsonOpts      *options.BSONOptions
        registry      *bsoncodec.Registry
        clientSession *session.Client
        err error
    }
// db.collection.getIndexes() 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
    );

    // 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
    );

    // Set compound index on address fields with hashed zipcode
    commandResult = 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
    );

    // Set hidden index
    commandResult = await customerCollection.createIndex(
      { profileCompletenessScore: 1 },
      { hidde: true }
    );

    console.log(
      "Command: db.customer.createIndex({profileCompletenessScore: 1}, {hidden: true}) | 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.createIndex({name: 1}, {name: "my_name_idx"}) | Result:  my_name_idx

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

Command: db.customer.createIndex({profileCompletenessScore: 1}, {hidden: true}) | Result:  profileCompletenessScore_1

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'
  },
  {
    v: 2,
    key: { profileCompletenessScore: 1 },
    name: 'profileCompletenessScore_1'
  }
]

NOTES

  • Use NodeJS “indexes()” method from the package “mongodb“.
  • Method signatures are-
    • indexes(options?: IndexInformationOptions): Promise<Document[]>
# db.collection.getIndexes() 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,
    )

    # 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,
    )

    # 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,
    )

    # Set hidden index
    command_result = customer_collection.create_index(
        [("profileCompletenessScore", 1)],
        hidden=True,
    )

    print(
        "Command: db.customer.createIndex({profileCompletenessScore: 1}, {hidden: true}) | 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

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

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

Command: db.customer.createIndex({profileCompletenessScore: 1}, {hidden: true}) | Result: profileCompletenessScore_1

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')]}, 'profileCompletenessScore_1': {'v': 2, 'key': [('profileCompletenessScore', 1)], 'hidden': True}}

NOTES

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

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

public class GetIndexes {
    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
            String createIndexResult = customerCollection.createIndex(new Document("email", 1), new IndexOptions().unique(true));

            System.out.println("Command: db.customer.createIndex({email: 1}, {unique: true}) | Result: " + createIndexResult);

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

            System.out.println("Command: db.customer.createIndex({name: 1}, {name: "my_name_idx"}) | Result: " + createIndexResult);

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

            System.out.println("Command: db.customer.createIndex({"address.country": 1, "address.state" : 1, "address.zipcode" : "hashed"}) | Result: " + createIndexResult);

            // Set hidden index
            createIndexResult = customerCollection.createIndex(new Document("profileCompletenessScore", 1), new IndexOptions().hidden(true));

            System.out.println("Command: db.customer.createIndex({profileCompletenessScore: 1}, {hidden: true}) | Result: " + createIndexResult);

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

        }
    }
}

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

Command: db.customer.createIndex({profileCompletenessScore: 1}, {hidden: true}) | Result: profileCompletenessScore_1

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"}
{"v": 2, "key": {"profileCompletenessScore": 1}, "name": "profileCompletenessScore_1", "hidden": true}

NOTES

  • Use the method “listIndexes()” from MongoCollection.
  • Signatures of the method are-
    • ListIndexesIterable<Document> listIndexes()
    • <TResult> ListIndexesIterable<TResult> listIndexes(Class<TResult> resultClass)
    • ListIndexesIterable<Document> listIndexes(ClientSession clientSession)
    • <TResult> ListIndexesIterable<TResult> listIndexes(ClientSession clientSession, Class<TResult> resultClass)

Source Code

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

Related Methods

CommandDetails
db.collection.createIndex() Method Details

Leave a Comment


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