An explanation of the creation and use of indexes in MongoDB

Source: Internet
Author: User
Tags mysql in

indexes can often greatly improve the efficiency of queries. When you use queries in your system, you should consider establishing related indexes. Creating an index in MongoDB is relatively easy.

The index in MongoDB is conceptually the same as most relational databases such as MySQL. When you need to build an index in MySQL in some cases, this scenario is also appropriate for MongoDB.

Basic operations

An index is a data structure that collects a set of values for a particular field in a document. MongoDB's query optimizer can use this data structure to quickly find and sort documents (collection) in Collections (collection). To be precise, these indexes are implemented by B-tree indexes.

On the command line, you can create an index by calling the Ensureindex () function, which specifies one to multiple fields that require an index. Following the example in the previous essay, we then set up the index on the J field in the Things collection:

    1. > Db.things.ensureIndex ({j:1})

The Ensureindex () function is created only if the index does not exist.

Once the collection is indexed on a field, the random query for that field is accessed quickly. If there is no index, MongoDB iterates through all the key-value pairs, and then goes to the corresponding check-related fields.

    1. > Db.things.find ({j:2}); Query on indexed fields, faster
    2. {"_id": ObjectId ("4e24433dcac1e3490b9033be"), "X": 4, "J": 2}
    3. > Db.things.find ({x:3});//query on fields that are not indexed, you need to match fields on a per-field basis, slow
    4. {"_id": ObjectId ("4E244315CAC1E3490B9033BC"), "X": 3}

You can view all the indexes in the current collection by entering Getindexs () on the command line.

  1. > db.things.getIndexes ()
  2. [
  3. {
  4. "Name": "_id_",
  5. "NS": "Things.things",
  6. "Key": {
  7. "_ID": 1
  8. },
  9. "V": 0
  10. },
  11. {
  12. "_id": ObjectId ("4e244382cac1e3490b9033d0
  13. "NS": "Things.things",
  14. "Key": {
  15. "J": 1
  16. },
  17. "Name": "J_1",
  18. "V": 0
  19. }
  20. ]

Ability to return all indexes in the current database via Db.system.indexes.find ()

    1. > Db.system.indexes.find ()
    2. {"Name": "_id_", "ns": "Things.things", "key": {"_id": 1}, "V": 0}
    3. {"_id": ObjectId ("4e244382cac1e3490b9033d0"), "ns": "Things.things", "key": {"J": 1}, "name": "J_1", "V": 0}

Default Index

For each collection (except for the capped collection), the default is to create an index on the _id field, and this particular index cannot be deleted. The _id field is mandatory and is maintained by the database.

Nested keywords

In MongoDB, you can even build an index on an embedded document (embedded).

    1. > Db.things.ensureIndex ({"Address.city": 1})

Document as Index

Any type, including document, can be indexed:

  1. > Db.factories.insert ({name: "xyz", Metro:{city: "New York", State: "NY"});
  2. > Db.factories.ensureIndex ({metro:1});
  3. > Db.factories.find ({metro:{city: "New York", State: "NY"});//ability to query by index
  4. {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": <
  5. {"City": "New York", "state": "NY"}}
  6. > Db.factories.find ({metro:{$gte: {city: "New York"}});//ability to query by index
  7. {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}
  8. > Db.factories.find ({metro:{state: "NY", City: "New York"})//Cannot return results, the order of the fields is incorrect

An alternative to creating a document index is to create a composite index, for example:

  1. > Db.factories.ensureIndex ({"metro.city": 1, "Metro.state": 1})
  2. > Db.factories.find ({"metro.city": "New York", "metro.state": "NY"});
  3. {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}
  4. > Db.factories.find ({"metro.city": "New York"});
  5. {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}
  6. > Db.factories.find (). Sort ({"metro.city": 1, "New York": 1});
  7. {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}
  8. > Db.factories.find (). Sort ({"Metro.city": 1});
  9. {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}

Composite Keyword Index

In addition to the basic index of a single keyword, MONGODB supports a combination index of multiple keywords, as well as a basic index, and is also used with the Ensureindex () function, which can specify multiple keys.

    1. > Db.things.ensureIndex ({j:1,name:-1})

When an index is created, the number following the key indicates the direction of the index, with a value of 1 or -1,1 for ascending, and 1 for descending. Ascending or descending is not very relevant at random access time, when it is important to do a sort or range query.

If you are building a composite index such as a,b,c, you can use index queries on a,a,b and a,b,c.

Sparse indexes

Like sparse matrices, sparse indexes are indexed to documents that contain indexed fields.

Any sparse document that is missing a field will not be stored in the index, which is called a sparse index, which means that the missing field's document value is lost.

There is no difference between creating a sparse index and creating a full index. When querying using a sparse index, some document records that have missing fields may not be returned because the sparse index sub returns the fields that are indexed. It may be difficult to understand, but a few examples will make it easier to understand.

  1. > Db.people.ensureIndex ({title:1},{sparse:true})//Create a sparse index on the title field
  2. > Db.people.save ({name: "Jim"})
  3. > Db.people.save ({name: "Yang", title: "Prince"})
  4. > Db.people.find ();
  5. {"_id": ObjectId ("4e244dc5cac1e3490b9033d7"), "name": "Jim"}
  6. {"_id": ObjectId ("4e244debcac1e3490b9033d8"), "name": "Yang", "title": "Prince"}
  7. > Db.people.find (). Sort ({title:1})//The record containing the indexed field is returned
  8. {"_id": ObjectId ("4e244debcac1e3490b9033d8"), "name": "Yang", "title": "Prince"}
  9. > Db.people.dropIndex ({title:1})//After deleting the sparse index, all records are displayed
  10. {"Nindexeswas": 2, "OK": 1}
  11. > Db.people.find (). Sort ({title:1})
  12. {"_id": ObjectId ("4e244dc5cac1e3490b9033d7"), "name": "Jim"}
  13. {"_id": ObjectId ("4e244debcac1e3490b9033d8"), "name": "Yang", "title": "Prince"}

Unique index

MongoDB supports unique indexes, which makes it impossible to insert records that already exist on a unique index entry. For example, to ensure that both FirstName and LastName are unique, the command is as follows

    1. > Db.things.ensureIndex ({firstname:1,lastname:1},{unique:true})

The Missing key

When a document is saved to the collection as a unique index, any missing index fields are replaced with a null value, so you cannot insert two default records at the same time on a unique index. As follows:

    1. >db.things.ensureindex ({firstname:1}, {unique:true});
    2. >db.things.save ({lastname: "Smith"});
    3. >db.things.save ({lastname: "Jones"});//generates an error because FirstName will have two null.

Duplicate values:

A unique index cannot be created on a key with duplicate values, if you must create on such a key, then you want the system will save the first record, the remaining records will be deleted, only need to create the index when the dropdups this option can be

    1. >db.things.ensureindex ({firstname:1}, {unique:true, dropdups:true})
    2. Dropping Indexes

To delete an index on a specific collection:

    1. >db.collection.dropindexes ();

To delete an index in a collection:

    1. Db.collection.dropIndex ({x:1, Y:-1})

You can also perform command-in-the-go removal directly

    1. Db.runcommand ({dropindexes: ' foo ', index: {y:1}})//delete index of {y:1} in set foo
    2. Remove all indexes:
    3. Db.runcommand ({dropindexes: ' foo ', Index: ' * '})//delete all indexes in the set foo

Rebuild Index:

You can rebuild the index with the following command:

    1. Db.myCollection.reIndex ()
    2. Same as:
    3. Db.runcommand ({reIndex: ' mycollection '})

This is usually unnecessary, but it is useful to rebuild the index when the size of the collection changes very much and the collection occupies a lot of space on disk space. Rebuilding an index can be slow for a collection of large amounts of data.

Note:

The index in MongoDB is case-sensitive.

When an object is updated, it is only updated when these keys on the index change. Significantly improved performance. When an object grows or must be moved, all indexes must be updated, which is slow.

The index information is saved in the System.indexes collection, and the sample data is visible to run Db.system.indexes.find ().

There is a maximum limit on the size of the indexed field, which is currently close to bytes. It is possible to make an index on a field larger than this value, but the field is not indexed and may be removed in a later version.

Performance of indexes

Indexing makes it possible to get data through key fields, enabling quick querying and updating of data.

However, it is important to note that the index also increases the burden on some systems when inserting and deleting. When inserting data into a collection, the indexed fields must be added to the b-tree, so that the index is appropriate for the data set that reads far more than the write, and in some cases the index has side effects in the case of frequently written collections. However, most collections are read-frequent collections, so collections are useful in most cases.

Use sort () with no index required

If the data collection is small (usually less than 4M), use sort () instead of indexing to return the data. In this case, do the combination using limit () and sort ().

An explanation of the creation and use of indexes in 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.