The index of MongoDB

Source: Internet
Author: User

1. Introduction
The index is to speed up the query. If there is no index, MONGODB will do a table scan when querying, and if the collection is large, this query will be very slow. The keys are generally indexed when the query is created.
Index the Sort field, and MongoDB will error if the collection is too large to be sorted in memory if the non-indexed field SORT,MONGODB all the data into memory.
2. MongoDB CREATE index
Create an index using the Ensureindex command.
> Db.people.ensureIndex ({"username": 1});
The above statement indexes the username key of the People collection.
3. Combined Index
For composite queries or sorting, set up a composite index.
> Db.people.ensureIndex ({"Date":-1, "username": 1});
The index key is 1 or-1, which indicates the order in which the index is created, 1 is ascending, and 1 is reversed. If the index has only one key, the direction does not matter.
4. Indexing of embedded documents
The comments for the blog set are indexed by time:
> Db.blog.ensureIndex ({"Comments.date": 1});

5. Unique index
A unique index ensures that each key in the collection is a unique value.
> Db.people.ensureIndex ({"username": 1}, {"Uniqe": true});
When you create a unique index on an existing collection, you may already have duplicate values, which creates an index failure. Dropdups retains the first document, removing the values that are repeated later.
> Db.people.ensureIndex ({"username": 1}, {"Unique": true, "dropdups": true});

6. View the established index
The index is placed in the System.indexes collection.
> Db.system.indexes.find ();
You can view the index key, the name, and which collection it belongs to.
7. Deleting an index
By using the name of the index, dropindexes can be used to delete the index. The index name is queried by System.indexes.
> db.user.dropIndexes ({"Username_1": 1});

Address: http://blog.csdn.net/yonggang7/article/details/28100855

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.