Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

[MongoDB Learning Notes 22] Index Management of MongoDB

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 236

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report