As anyone who has used a database knows, database indexes are similar to book indexes and are used to help with quick searches.

MongoDB indexes are almost identical to those of relational databases.

db.user.getIndexes()
Copy the code
  1. Index creation

Mongodb uses ensureIndex to create indexes, such as:

db.user.ensureIndex({"name":1})
Copy the code

Creates an index on the name key of the user collection, where 1 indicates the direction of index creation. The value can be 1 or -1

In this case, we don’t give the index a name, mongodb will give us a default name as follows:

keyname1_dir1_keyname2_dir2... keynameN_dirNCopy the code

Keyname indicates the keyname and dir indicates the direction of the index. For example, in the example above, the name of the index we created is name_1

Indexes can also be created on multiple keys, known as federated indexes, as in:

> db.user.ensureIndex({"name":1."age":1})
Copy the code

This creates a joint index of name and age

In addition to the default mongodb index name, we can also specify a convenient name for ensureIndex by specifying a value of name, such as:

> db.user.ensureIndex({"name":1}, {"name":"IX_name"})
Copy the code

Thus, the name of the index we created is IX_name

  1. The only index

Like RDB, we can define a unique index by specifying the unique key true:

>db.user.ensureIndex({"name":1}, {"unique":true})
Copy the code

3. Check the index we created

Indexes are stored in each database’s System. indexes collection, which can only be modified with ensureIndex and dropIndexes. You cannot manually insert or modify the indexes.

To find all the indexes in the database, go to > db.system.indexes.

> db.system.indexes.find() 
{ "v" : 1."key" : { "_id" : 1 }, "ns" : "test.entities"."name" : "_id_" } 
{ "v" : 1."key" : { "_id" : 1 }, "ns" : "test.blog"."name" : "_id_" } 
{ "v" : 1."key" : { "_id" : 1 }, "ns" : "test.authors"."name" : "_id_" } 
{ "v" : 1."key" : { "_id" : 1 }, "ns" : "test.papers"."name" : "_id_" } 
{ "v" : 1."key" : { "_id" : 1 }, "ns" : "test.analytics"."name" : "_id_" } 
{ "v" : 1."key" : { "_id" : 1 }, "ns" : "test.user"."name" : "_id_" } 
{ "v" : 1."key" : { "_id" : 1 }, "ns" : "test.food"."name" : "_id_" } 
{ "v" : 1."key" : { "_id" : 1 }, "ns" : "test.user.info"."name" : "_id_" } 
{ "v" : 1."key" : { "_id" : 1 }, "ns" : "test.userinfo"."name" : "_id_" } 
{ "v" : 1."key" : { "name" : 1 }, "ns" : "test.user"."name" : "IX_name" }
Copy the code

4. Delete indexes

If the index is no longer useful, drop it using dropIndexes:

> db.runCommand({"dropIndexes":"user"."index":"IX_name"{})"nIndexesWas" : 2."ok" : 1 }
Copy the code

Ok indicates that the deletion is successful