MongoDB - Indexing

To create an index in the Mongo Shell,

 
  db.collection.createIndex().

  db.collection.createIndex( ,  )

The following example creates a single key ascending index on the name field:

 
  db.collection.createIndex( { regno: 1 } )

Viewing all the indexes

 
  db.collection.getIndexes()

Index Names

 
  db.student.createIndex({regno:1},{name:"index on regno"})

Dropping an Index

 
  db.student.dropIndex("regno_1")

Dropping all Indexes

 
  db.student.dropIndexes("regno_1","name_1")
  db.student.dropIndexes()

Creating a Single Field Index

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

Creating a Compound Index

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

Creating a Multi key index for the data given below

 
  { 
    "_id" : ObjectId("60544b082c7bb6a353bf817a"), "name" : "satish", 
    "marks" : [
     {"cat1" : { "maths" : 30, "chem" : 88, "eng" : 80 } },
     { "cat2" : { "maths" : 90, "chem" : 40, "eng" : 33 } } 
    ] 
    }
    
    db.students1.createIndex({"marks.cat1.maths":1})

Creating a Text index

 
  db.comments.createIndex({post:"text"})

Searching using the text index

 
  db.stores.find( { $text: { $search: "java coffee shop" } } )