Get the App
SLTechnology News&Howtos  ›  Database  › 

[MongoDB Learning Notes 22] Index Management of MongoDB

Shulou Source: shulou.com Published: 2022-06-01 14:24:37 10月31日 Update

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"}] >

Tags: Indexes functions identifiers data functions examples information databases formats steps building one notes learning management Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Linux MySQL MariaDB Shulou Information