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 21] compound Index of MongoDB

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

Share

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

The values of the index are arranged in a certain order, so it is faster to search and sort the document using the index key, but the index is useful only if the index is used for sorting first.

For example, in the following sort, the index on "username" does not work:

> db.users.find () .sort ({"age": 1, "username": 1})

The above command sorts first by age and then by username, so username is not very useful. To optimize this sort, you need to build indexes on age and username:

> db.users.ensureIndex ({"age": 1, "username": 1})

This creates a composite index (compound index) on the users collection, which is an index built on multiple fields.

First, choose the direction of the index

Indexes are in ascending order by default, and when querying multiple indexes, you may need to make the direction of the index keys different. For example:

> db.users.ensureIndex ({"age": 1, "username":-1})

Or

> db.users.ensureIndex ({"age":-1, "username": 1})

The two are equivalent.

The age is sorted in the order of 0-9, the order in which Zmura is installed in each age group, or the user name is sorted smoothly by Amurz, sorted by 9-0 in each user group.

Second, use implicit indexes

Composite indexes can be represented as different indexes for different queries. If there is an index of {"age": 1, "username": 1}, the age field is automatically sorted as if there is an index of {"age": 1}.

It can be inferred that if there is {"a": 1, "b": 1. .. index of "z": 1}, there will be {"a": 1}, {"a": 1, "b": 1}, {"a": 1, "b": 1, "c": 1}. . A series of indexes

However, {"b": 1} or {"b": 1, "c": 1} cannot be used as an index to optimize the query, meaning that the query can only be optimized in the order of the index.

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: 0

*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

Database

Wechat

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

12
Report