Part IV Performance Chapter Tenth MongoDB index

Source: Internet
Author: User
Tags install mongodb mongodb query

1. Introduction
MongoDB provides a variety of index support, the index information is saved in System.indexes, and the default is always to create an index _id, its index using the basic and MySQL relational database, can actually say, An index is another layer of system above a data storage system, so it is not surprising that different types of storage have identical or similar index implementations and interfaces.

2. Base Index
Create index on field age, 1 (ascending), 1 (Descending)

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >db.user.ensureindex ({age:1}) {        "createdcollectionautomatically": false,        "Numindexesbefore": 1,        " Numindexesafter ": 2,        " OK ": 1}> db.user.getIndexes (); [        {                "V": 1,                "key": {                        "_id": 1                },                "name": "_id_",                "ns": "Test.user"        },        {                "V": 1,                "key": {                        "age": 1                },                "name": "Age_1",                "ns": "Test.user"        }]> </span >
Description

The above shows a total of 2 indexes, where _id is the index created automatically when creating the table, this index cannot be deleted.

When the system already has a large amount of data, the process of creating the index is a very time-consuming process, we can execute in the background, only need to make background:true.

>db.user.ensureindex ({age:1},{background:true})


3. Document Index

An index can be any type of field, even a document.

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> Db.factories.insert ({name: "www", addr:{city: "BJ", State: "Beijing"}); Writeresult ({"ninserted": 1}) </span>
Create an index on the addr column

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> db.factories.ensureIndex ({addr:1}); {        "createdcollectionautomatically": false,        "Numindexesbefore": 1,        "Numindexesafter": 2,        "OK": 1} </span>
The following query will use the index we just created

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> Db.factories.find ({addr:{city: "BJ", State: "Beijing"}); {"_id": ObjectId ("54A935B579CEADF5FA8E2EC1"), "name": "www", "addr": {"City": "BJ", "state": "Beijing"}}</span >
However, the following query does not use indexes because the order of the queries is different from the order in which the indexes are established

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> Db.factories.find ({addr:{state: "Beijing", City: "BJ"});</span>


4. Combined Index

As with other database products, MongoDB also has a combined index, Next I'll set up a composite index on addr.ctiy and addr.state, when creating a composite index, the 1 after the field indicates ascending, 1 means descending, 1 or 1 is related to the time of the sort or the query within the specified range.

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> Db.factories.ensureIndex ({"addr.city": 1, "Addr.state": 1}); {        "createdcollectionautomatically": false,        "Numindexesbefore": 2,        "Numindexesafter": 3,        "OK": 1} > </span>

At this point, the following query uses this index

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> Db.factories.find ({"addr.city": "BJ", "addr.state": "Beijing"}); {"_id": ObjectId ("54A935B579CEADF5FA8E2EC1"), "name": "www", "addr": {"City": "BJ", "state": "Beijing"}}> < /SPAN>
<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> Db.factories.find ({"addr.city": "BJ"}); {"_id": ObjectId ("54A935B579CEADF5FA8E2EC1"), "name": "www", "addr": {"City": "BJ", "state": "Beijing"}}> < /SPAN>
<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> Db.factories.find (). Sort ({"addr.city": 1, "Addr.state": 1}); {"_id": ObjectId ("54A935B579CEADF5FA8E2EC1"), "name": "www", "addr": {"City": "BJ", "state": "Beijing"}}> < /SPAN>
<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> Db.factories.find (). Sort ({"Addr.city": 1}) {"_id": ObjectId ("54A935B579CEADF5FA8E2EC1"), "name": "www", " Addr ": {" City ":" BJ "," state ":" Beijing "}}> </span>

5. Unique index

You only need to specify Unique:true in the Ensureindex command to create a unique index, such as inserting two records into a table T4:

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> Db.t4.insert ({firstname: "Wang", LastName: "WU"}); Writeresult ({"ninserted": 1}) > Db.t4.insert ({firstname: "Wang", LastName: "Liu"}); Writeresult ({"ninserted": 1}) > </span>
Create a unique index in the T4 table

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> db.t4.ensureIndex ({firstname:1,lastname:1},{unique:true}); {        "createdcollectionautomatically": false,        "Numindexesbefore": 1,        "Numindexesafter": 2,        "OK": 1} </span>
View Index:

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> db.t4.getIndexes ();  [        {                "V": 1,                "key": {                        "_id": 1                },                "name": "_id_",                "ns": "Test.t4"        },        {                "V": 1,                "unique": true,                "key": {                        "FirstName": 1,                        "LastName": 1                },                "name": "Firstname_1_las Tname_1 ",                " ns ":" Test.t4 "        }]</span>

6. Mandatory use of Indexes

The hint command can force an index to be used

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> Db.t5.insert ({name: "Wangwu", age:20}); Writeresult ({"ninserted": 1}) > </span>
Create an index

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> db.t5.ensureIndex ({name:1,age:1}) {        "createdcollectionautomatically": false,        "Numindexesbefore": 1,        "Numindexesafter": 2,        "OK": 1}</span>
query (no index used)

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> Db.t5.find ({age:{$lt: +}). Explain () {        "cursor": "Basiccursor",        "Ismultikey": false,        "n": 1,        "Nscannedobjects": 1,        "nscanned": 1,        "Nscannedobjectsallplans": 1,        "Nscannedallplans": 1,        " Scanandorder ": false,        " IndexOnly ": false,        " Nyields ": 0,        " nchunkskips ": 0,        " Millis ": 0,        " Server ":" localhost.localdomain:27017 ",        " Filterset ": false}</span>
force the use of indexes

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> Db.t5.find ({age:{$lt: +}). Hint ({name:1,age:1}). Explain () {"cursor": "Btreecursor name_1_age_1", "  Ismultikey ": false," n ": 1," nscannedobjects ": 1," nscanned ": 1," Nscannedobjectsallplans "        : 1, "Nscannedallplans": 1, "Scanandorder": false, "indexOnly": false, "Nyields": 0,                                "Nchunkskips": 0, "Millis": PNs, "Indexbounds": {"name": [[                                {"$minElement": 1},                         {"$maxElement": 1}                                ]], "age": [[ {"$minElement": 1},                                {"$maxElement": 1 }]]}, "Server": "localhost.localdomain:27017", "Filterset" : false}</span>

7. Delete Index

Deleting an index is divided into deleting all indexes on a table and deleting an index of a table, as follows:

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;" >> db.t5.dropIndexes (); {        "Nindexeswas": 2,        "MSG": "non-_id indexes dropped for collection",        "OK": 1}> </span>
Remove the FirstName index from the T4 table

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:14PX;"  >> db.t4.dropIndex ({firstname:1}) {        "Nindexeswas": 2,        "OK": 0,        "errmsg": "Can ' t find index with key:{ firstname:1.0} "}> </span>

-----------------------------------MongoDB Series article update-----------------------

The first part of the basic chapter into MongoDB

The first part of the basic chapter II install MongoDB

Part I basic chapter III MONGODB architecture

The first part of the basic chapter fourth MongoDB Quick Start

The first part of the basic chapter Fourth MongoDB query

Part Two application chapter Fifth MongoDB advanced query

Part Two application chapter sixth MongoDB Gridfs

Part Two application chapter seventh MongoDB MapReduce

Part III Management chapter eighth MONGODB service Management

Part III Management Chapter Nineth the MongoDB Shell system command, user command

Part III Management Chapter Nineth of the MongoDB shell eval, process

Part IV Performance Chapter Tenth MongoDB 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.