[MongoDB] Index

Source: Internet
Author: User

Summary

In the previous article, a method for analyzing MongoDB performance was introduced, and this article will describe the use of indexes, which is also a common way of query optimization. Here's an introduction to the index if you create it.

Related articles

Getting started with [MongoDB]

[MongoDB] additions and deletions change

[Mongodb]count,gourp,distinct

[Mongodb]mapreduce

[MongoDB] Profiling Performance Analysis

[MongoDB] Index

Index

Index

We create an index for the name field above the collection of users

Db.users.ensureIndex ({"name":1})

Query the collection which indexes have been created above

Db.users.getIndexes ()

It was discovered through a query that the collection created an index for ID and name, where _id is the default index.

Delete the index above the field name

Db.users.dropIndex ({"name":1})

Composite Index

Create a composite index above name and age

Db.users.ensureIndex ({"name":1,"Age":-1 })

When the composite index is created, a query based on name and age will use that index, or a name-based query will use that index, but only the age-based query would not use the composite index.

Therefore, if you want to use a composite index, you must include the first n index columns in the composite index in the query criteria. However, if the order of key values in the query condition is inconsistent with the order of creation in the composite index, MongoDB can intelligently help us adjust that order so that the composite index can be used by the query.

Unique index

Indexes created by default are not unique indexes, if creating unique indexes requires the unique parameter set to True

Create a unique index for name

Db.users.ensureIndex ({"name":1},{"unique":  True})

If the duplicate name value is inserted at this point, an error will be

Summarize

The creation, deletion, query, and unique creation of the index are described here.

[MongoDB] Index

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.