MongoDB Learning (3)--Index

Source: Internet
Author: User

Indexes can be used to optimize queries, and in some specific types of queries, indexes are essential. Choosing the right index for a collection is the key to improving performance.

First, mock data.

 for (i = 0; i < 1000000; i++) {    Db.users.insert ({        "i": I,        "username": "user" + I,        
     "Age": Math.floor (Math.random () *),        new  Date ()    });

1 million data will be created in the database, a little bit slower, and will need to wait.

We can use the explain () function to see what MongoDB does in the course of executing a query. Execute the following command to find the user named user1000.

Db.users.find ({username: "user1000"}). Explain ()

The results were as follows:

{    "Cursor": "Basiccursor",    "Ismultikey":false,    "N": 1,    "Nscannedobjects": 1000000,    "Nscanned": 1000000,    "Nscannedobjectsallplans": 1000000,    "Nscannedallplans": 1000000,    "Scanandorder":false,    "IndexOnly":false,    "Nyields": 7813,    "Nchunkskips": 0,    "Millis": 411,    "Server": "user:27017",    "Filterset":false}

The meaning of each field is then described in detail, and now we just need to know that "n" means the number of query results, "nscanned" indicates the total number of files that MongoDB scanned during the completion of this query, and "Millis" represents the number of milliseconds this query takes. As you can see, the entire collection is traversed for the purpose of finding User1000,mongodb, consuming 411 milliseconds.

To refine the query, we can end the query and return the results when we find a result. The command is as follows:

Db.users.find ({username: "user1000"}). Limit (1). Explain ()

The results are as follows:

{    "Cursor": "Basiccursor",    "Ismultikey":false,    "N": 1,    "Nscannedobjects": 1001,    "Nscanned": 1001,    "Nscannedobjectsallplans": 1001,    "Nscannedallplans": 1001,    "Scanandorder":false,    "IndexOnly":false,    "Nyields": 7,    "Nchunkskips": 0,    "Millis": 1,    "Server": "user:27017",    "Filterset":false}

You can see that the number of scanned documents and the time consumed are much less, but if we are looking for user999999,mongodb or traversing the collection to find it. And as the number of users increases, the query becomes slower.

In this case, creating an index is a great solution: indexes can organize data based on a given field, allowing MongoDB to find the target document very quickly. Use the following command to create an index on the username field.

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

And then execute the previously executed statements.

Db.users.find ({username: "user1000"}). Explain ()

The results are as follows:

{    "Cursor": "Btreecursor username_1",    "Ismultikey":false,    "N": 1,    "Nscannedobjects": 1,    "Nscanned": 1,    "Nscannedobjectsallplans": 1,    "Nscannedallplans": 1,    "Scanandorder":false,    "IndexOnly":false,    "Nyields": 0,    "Nchunkskips": 0,    "Millis": 0,    "Indexbounds" : {        "Username" : [            [                "user1000",                "user1000"            ]        ]    },    "Server": "user:27017",    "Filterset":false}

Then you'll find that the query gets a lot faster, almost instantaneously, and that's the effect of using the index. However, the index also has a price, and for each index that is added, each write operation (insert, UPDATE, delete) takes more time. This is because MongoDB not only updates the document, but also updates all the indexes on the collection when the data changes. Therefore, MongoDB restricts a maximum of 64 indexes on each collection. Typically, you should not have more than two indexes on a particular collection.

When an index is built on more than one field, we call it a composite index and create the following statement:

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

A composite index can be useful if there are multiple sort directions in the query or if there are multiple keys in the query condition.

The way MongoDB uses this index depends on the type of query. Here are three main ways to do this.

The first type:

Db.users.find ({"Age": +}). Sort ({"username":-1})

This is a point query that is used to find a single value (although the document containing this value is multiple). Because of the second field in the index, the query results are already ordered. This type of query is very efficient.

The second type:

Db.users.find ({"Age": {"$gte": +, "$lte": 30}})

This is a multivalued query that finds documents that match multiple values, and MongoDB uses the first key in the index "age" to get a matching document. If you use "username" to make a query, the index does not work.

The third type:

Db.users.find ({"Age": {"$gte": +, "$lte": +}}). Sort ({"username": 1})

This is also a multivalued query, similar to the previous one, but this time the query results need to be sorted. MongoDB needs to sort the results in memory, which is less efficient than the previous one.

The command to delete the index is as follows:

Db.users.dropIndex (' Age_1_username_1 ')

Removes the index named ' Age_1_username_1 ' in the Users collection.

The index information for all databases is stored in the System.indexes collection, which is a reserved collection that cannot be inserted or deleted in the document, and can only be manipulated by Ensureindex and Dropindex.

Use the following command to get the index information on the Users collection:

Db.users.getIndexes ()

The results are as follows:

[    {        "V": 1,        "Key" : {            "_ID": 1        },        "Name": "_id_",        "NS": "Test.users"    },    {        "V": 1,        "Key" : {            "Username": 1        },        "Name": "Username_1",        "NS": "Test.users"    },    {        "V": 1,        "Key" : {            "Age": 1,            "Username": 1        },        "Name": "Age_1_username_1",        "NS": "Test.users"    }]

MongoDB Learning (3)--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.