"MongoDB Learning Note 21" MongoDB Composite Index

Source: Internet
Author: User
Tags sorts

The values of the indexes are arranged in a certain order, so it is faster to search the document by using the index key, but only when the index is first used to sort the index;

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

> Db.users.find (). Sort ({"Age": 1, "username": 1})


The above command first sorts according to the age, sorts according to username, so username function is not big. To optimize this sort, you need to index 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, select the direction of the index

Indexes are ascending by default and may need to be different in the direction of index keys when querying multiple indexes. 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 0-9 order, in the order in which the z-a are installed in each age group, or the user name is sorted by 9-0 in each user group by a A-Z smooth sort.

Ii. using an implicit index

Composite indexes can behave as different indexes on different queries. If there is a {"Age": 1, "username": 1} Index, the age field is automatically sorted, as if there is an index of {"Age": 1};

It can be inferred, if there is {"A": 1, "B": 1 ... " Z ": 1} index, 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 refine the query, meaning the query can only be optimized in index order.


This article is from the "Margin with Wish" blog, please be sure to keep this source http://281816327.blog.51cto.com/907015/1600866

"MongoDB Learning Note 21" MongoDB Composite Index

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.