[MongoDB Learning Notes 22] Index Management of MongoDB
Use the ensureIndex function to create an index of the collection.
For the collection, each index only needs to be created once, and repeated creation has no effect.
> show collections system.indexes users
The index metadata of all databases is stored in the collection of system.indexs
Use the getIndexes function to view the index information on a given collection:
> db.users.getIndexes () [{"v": 1, "key": {"_ id": 1}, "name": "_ id_", "ns": "blog.users"}, {"v": 1 "key": {"username": 1}, "name": "username_1", "ns": "blog.users"}, {"v": 1, "key": {"age": 1 "username": 1}, "name": "age_1_username_1", "ns": "blog.users"}] >
It can be adapted to the dropIndex function to delete the specified index:
> db.users.dropIndex ({"username": 1}) {"nIndexesWas": 3, "ok": 1} > db.users.getIndexes () [{"v": 1, "key": {"_ id": 1}, "name": "_ id_" "ns": "blog.users"}, {"v": 1, "key": {"age": 1, "username": 1}, "name": "age_1_username_1" "ns": "blog.users"}] >
In the above example, you can see that the default format of index identification is keyname1_dir1_keyname2_dir. .keynameN _ DirN
You can also specify an identity name:
> db.users.ensureIndex ({"username": 1}, {"name": "firstname"}) {"createdCollectionAutomatically": false, "numIndexesBefore": 2, "numIndexesAfter": 3, "ok": 1} > db.users.getIndexes () [{"v": 1 "key": {"_ id": 1}, "name": "_ id_", "ns": "blog.users"}, {"v": 1, "key": {"age": 1 "username": 1}, "name": "age_1_username_1", "ns": "blog.users"}, {"v": 1, "key": {"username": 1} "name": "firstname", "ns": "blog.users"}] >
To modify an index: delete index-> create index
Deleting an index can specify the index identity directly, for example:
> db.users.dropIndex ("firstname") {"nIndexesWas": 3, "ok": 1} > db.users.getIndexes () [{"v": 1, "key": {"_ id": 1}, "name": "_ id_" "ns": "blog.users"}, {"v": 1, "key": {"age": 1, "username": 1}, "name": "age_1_username_1" "ns": "blog.users"}] >