As with the database, the database index is similar to the index of a book, and is used to help you find it quickly. The index of the  MONGODB is almost identical to the index of the relational database. 1. Index creation  MONGODB uses Ensureindex to create an index, such as: db.user.ensureindex ({"Name": 1}) indicates that an index is created in the name key of the user collection. Here 1 represents the direction of the index creation, can take a value of 1 and -1 here, we do not give the index name, MongoDB will give us a default name, the rule is Keyname1_dir1_keyname2_dir2...keynamen_ Dirn keyname represents the key name, dir represents the direction of the index, for example, the above example we create the index name is the name_1 index can also be created on multiple keys, that is, a federated index, such as: > Db.user.ensureIndex ({"Name": 1, "Age": 1}) This creates a federated index of name and age in addition to the name of the default index for MongoDB, We can also go to a convenient name, by specifying the value of name for Ensureindex, such as: > Db.user.ensureIndex ({"Name": 1},{"name": "Ix_name"}) this , the name of the index we created was called Ix_name 2. Unique index similar to an RDB, we can also define a unique index by specifying a unique key True: >db.user.ensureindex ({"Name": 1},{"unique": true}) 3. View our established index The information of the index exists in the System.indexes collection of each database, only Ensureindex and dropindexes can be modified for this collection, and the collection cannot be inserted or modified manually. through > Db.system.indexes.find () can find multiple indexes in the database: > db.system.indexes.find () {"V": 1, "key": {"_id": 1}," ns ":" Test.entities "," name ":" _id_ "} {" V ": 1," key ": {" _id ": 1}," ns ":" Test.blog "," name ":" _i D_ "} {" 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"} 4. Remove index If the index is useless, you can use dropindexes to delete it: > Db.runcommand ({"dropindexes": "User", "index": "Ix_name"}) {"Nindexeswas": 2, "OK": 1} ok means delete succeeded
Add an index to MongoDB