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