Specify Name for text Index

Changed in MongoDB 4.2

Starting in version 4.2, for featureCompatibilityVersion set to "4.2" or greater, MongoDB removes theIndex Name Length limit of 127 byte maximum. In previousversions or MongoDB versions withfeatureCompatibilityVersion (fCV) set to"4.0", index names must fall within thelimit.

The default name for the index consists of each indexed field nameconcatenated with _text. For example, the following command createsa text index on the fields content, users.comments, andusers.profiles:

  1. db.collection.createIndex(
  2. {
  3. content: "text",
  4. "users.comments": "text",
  5. "users.profiles": "text"
  6. }
  7. )

The default name for the index is:

  1. "content_text_users.comments_text_users.profiles_text"

Specify a Name for text Index

You can pass the name option to thedb.collection.createIndex() method:

  1. db.collection.createIndex(
  2. {
  3. content: "text",
  4. "users.comments": "text",
  5. "users.profiles": "text"
  6. },
  7. {
  8. name: "MyTextIndex"
  9. }
  10. )

Use the Index Name to Drop a text Index

Whether the text index has the default nameor you specified a name for the text index,to drop the text index, pass the index nameto the db.collection.dropIndex() method.

For example, consider the index created by the following operation:

  1. db.collection.createIndex(
  2. {
  3. content: "text",
  4. "users.comments": "text",
  5. "users.profiles": "text"
  6. },
  7. {
  8. name: "MyTextIndex"
  9. }
  10. )

Then, to remove this text index, pass the name "MyTextIndex" to thedb.collection.dropIndex() method, as in the following:

  1. db.collection.dropIndex("MyTextIndex")

To get the names of the indexes, use thedb.collection.getIndexes() method.