How do I display the indexes of a collection in MongoDB?

MongoDBDatabaseBig Data Analytics

In order to display the indexes of a collection, you can use getIndexes(). The syntax is as follows −

db.yourCollectionName.getIndexes();

To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.indexDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f7c4f2f684a30fbdfd599")
}
> db.indexDemo.insertOne({"StudentName":"Mike","StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f7c552f684a30fbdfd59a")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.indexDemo.insertOne({"StudentName":"Carol","StudentAge":20});

The following is the output −

{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f7c5e2f684a30fbdfd59b")
}
> db.indexDemo.find().pretty();
{
   "_id" : ObjectId("5c8f7c4f2f684a30fbdfd599"),
   "StudentName" : "Larry",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c8f7c552f684a30fbdfd59a"),
   "StudentName" : "Mike",
   "StudentAge" : 24
}
{
   "_id" : ObjectId("5c8f7c5e2f684a30fbdfd59b"),
   "StudentName" : "Carol",
   "StudentAge" : 20
}

Here is the query to create indexes −

> db.indexDemo.createIndex({"StudentName":-1,"StudentAge":-1});

The following is the output:

{
   "createdCollectionAutomatically" : false,
   "numIndexesBefore" : 2,
   "numIndexesAfter" : 3,
   "ok" : 1
}

Here is the query to display the indexes of a collection. The collection name is “indexDemo” −

> db.indexDemo.getIndexes();

The following is the output −

[
   {
      "v" : 2,
      "key" : {
         "_id" : 1
      },
      "name" : "_id_",
      "ns" : "test.indexDemo"
   },
   {
      "v" : 2,
      "key" : {
         "StudentName" : -1
      },
      "name" : "StudentName_-1",
      "ns" : "test.indexDemo"
   },
   {
      "v" : 2,
      "key" : {
         "StudentName" : -1,
         "StudentAge" : -1
      },
      "name" : "StudentName_-1_StudentAge_-1",
      "ns" : "test.indexDemo"
   }
]
raja
Published on 29-Mar-2019 13:33:55
Advertisements