The index of MongoDB

Source: Internet
Author: User

Index is used to speed up the query, here does not explain the principle of indexing and data structure, in fact, most of the database index is b+tree, want to understand the students can see the index principle, to master how to configure the best index for the query will be some difficulty.

The MongoDB index is almost the same as the index of the relational database. The best way to optimize relational database indexing is also for MongoDB.
Let's take an example and now insert multiple documents into the collection:

Db.lf.Insert({"Name": "LF", "age": at, "IsActive":true}) Db.lf.Insert({"Name": "LF", "age": -, "IsActive":false}) Db.lf.Insert({"Name": "AAAA", "Age": -, "IsActive":false}) Db.lf.Insert({"Name": "BBBB", "Age": -, "IsActive":false}) Db.lf.Insert({"Name": "CCCC", "Age": -, "IsActive":false}) Db.lf.Insert({"Name": "AAAAA", "Age": -, "IsActive":false}) Db.lf.Insert({"Name": "BBBB", "Age": -, "IsActive":true}) Db.lf.Insert({"Name": "BBBB", "Age": +, "IsActive":false}) Db.lf.Insert({"Name": "Rrrr", "Age": One, "IsActive":true})

Next, we should create an index.

Create an index

To find by the name key, you can build an index on this key to increase the query speed.
Use the Ensureindex method to create an index:

db.lf.ensureIndex({"name":1})

Creating an index on a key accelerates the query for that key, but may not help for other queries, even if the query contains keys that are indexed.
So how do you see which indexes you've created?

View Index

You can use Db.system.indexes.find () to view the indexes you have created.

As you can see, the ID is bound to have an index, and we create the name index in the back.

Here is a concept called table scan , where a table scan is the search for content in a collection without indexes, from the first to the last. When the collection is too large, this need to look very slow, so we have to avoid the table scan.

Delete Index

Use the dropindexes command to delete the index.
For example:

> Db.runcommand ({"Dropindexes":"LF" ,"Index":"*"}){"Nindexeswas" : 2,"MSG" : "non-_id indexes dropped for collection","OK" : 1}> Db.lf.ensureIndex ({"Name":1,"Age":1}) > Db.lf.ensureIndex ({"Name":1,"Age":-1}) > Db.system.indexes.find () {"V" : 1,"Key" :{"_id" : 1},"NS" : "TEST.LF","Name" : "_id_"}{"V" : 1,"Key" :{"_id" : 1},"NS" : "TEST.LF","Name" : "_id_"}{"V" : 1,"Key" :{"_id" : 1},"NS" : "TEST.LF","Name" : "_id_"}{"V" : 1,"Key" :{"Name" : 1,"Age" : 1},"NS" : "TEST.LF","Name": "Name_1_age_1"}{"V" : 1,"Key" :{"Name" : 1,"Age" :-1},"NS" : "TEST.LF","Name" : "Name_1_age_-1"}

As you can see, all you create will have a name, which is all you have to do when you delete the corresponding index.

If you create an index this way by {"Age": 1, "name": 1,}, MongoDB is organized as follows:

The user name is installed in ascending alphabetical order, and groups of the same name are sorted by age.

The disadvantage of creating an index is that each insert, update, and delete incur additional overhead because the database needs to perform these operations, as well as to mark them in the index of the collection. Therefore, create as few indexes as possible.
In general, if the query is going to return more than half of the results in the collection, using a table scan will be faster than almost every document, so there is no need to use the index if the query has a key, or if it is true that the value of the Boolean type is true.

Extended Index

Suppose you have a collection that stores the user's state information. Now you want to query the user and the date to take out the most recent state of a user. We may establish the following index:

db.users.ensureIndex({"user":1,"date":-1})

This makes querying for users and dates very fast, but not the best way.
Because the app will have millions of users, each person will have dozens of status updates per day. If the index value of each user state we use a page-like disk control, the database will load different pages into memory for each "up-to-date" query. If the site is too hot, memory can not put all indexes, it will be very slow. If you change the order of the indexes {"Date":-1, "User": 1}, the database can save the last days ' indexes in memory, effectively reducing the memory exchange, so that querying any user's latest state will be much faster.

indexing keys in an inline document

So how does the index work on NoSQL's complex and flexible embedded documents?
In fact, there is no difference between ordinary, or using the dot operator:

db.blog.insert(  {    "title":" blog",    "author":    {      "name":"lf",      "email":"[email protected]"    }    })

To create an index for author.name:

db.blog.ensureIndex({"author.name":1})

There is no difference between a key index and a normal key index for an embedded document, so the two can be combined to form a composite index.

Index name

Each index in the collection has a string-type name that uniquely identifies the index, which the server uses to delete or manipulate the index. By default, the index name is similar

keyname1_dir1_keyname2_dir2

This form, where KeyName represents the key of the index, dir represents the direction of the index (1 or-1). Of course, we can also specify the name of the index by Ensureindex:

db.blog.ensureIndex({"author.name":1},{"name":"author_name_index"})

Note that the custom index name cannot be modified, and can only be rebuilt by deleting the index.

Unique index

A unique index ensures that the specified key for each document in the collection has a unique value. If you want to ensure that the username key for the document has a different value:

db.lf.ensureIndex({"username":1},{"unique":true})

By default, insert does not detect whether a document has been inserted, so in order to avoid inserting a document that contains values that are duplicates of unique keys, a secure insert may be used to meet the requirements.

Eliminate Duplicates

When we create a unique index for an existing collection, some values may have been duplicated, so a failure is created. We may want to delete all documents that contain duplicate values, so we can use the Dropdups method to preserve the first document we found and remove the next duplicate-valued document:

db.lf.ensureIndex({"username":1},{"unique":true,"dropDups":true})

Of course, if it is important data, this is a bit reckless, or write a script preprocessing is better.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The index of MongoDB

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.