About the role and usage of MongoDB indexes--mongodb

Source: Internet
Author: User
Tags mongodb mongodb query

There is not a lot to know about MongoDB, but in this limited cognition, it is found that its nosql features are distinct.

Because the nosql of the relationship is very interesting and feels more comfortable than relational databases like MySQL.

So we are concerned about the MongoDB database, hoping to delve deeper into the powerful place where it can be used more skillfully.

These articles are the study of the initial stage of learning something to be reproduced over the

Index +++++++++++++++++++++++++++++++++++


Indexes can often greatly improve the efficiency of queries. When using queries in your system, you should consider establishing related indexes. It is relatively easy to create indexes in MongoDB. The indexes in MongoDB are conceptually the same as most relational databases, such as MySQL. When you are in a situation where you need to index in MySQL, this scenario is also suitable for mongodb.
Basic operations
An index is a data structure that collects the values of a specific field in a set of Chinese documents. The MongoDB query optimizer can use this data structure to quickly find and sort documents (collection) in a collection (collection). To be exact, these indexes are implemented through B-tree indexes.
On the command line, you can create an index by calling the Ensureindex () function, which specifies a field to multiple fields that require an index. Following the example in the previous essay, we then things the J field in the collection:
1. > Db.things.ensureIndex ({j:1})
The Ensureindex () function is created only if the index does not exist.
Once a collection has been indexed on a field, the random query to that field is accessed quickly. If there is no index, MONGODB will iterate through all the key-value pairs and then go to the corresponding check-related fields.
1. > Db.things.find ({j:2}); Query on indexed fields, fast
2.
3. {"_id": ObjectId ("4e24433dcac1e3490b9033be"), "X": 4, "J": 2}
4.
5. > Db.things.find ({x:3});//Queries on fields that are not indexed, need to match one field to the other, slow
6.
7. {"_id": ObjectId ("4E244315CAC1E3490B9033BC"), "X": 3}
You can view all indexes in the current collection by entering Getindexs () on the command line.
1. > db.things.getIndexes ()
2.
3. [
4.
5. {
6.
7. "Name": "_id_",
8.
9. "NS": "Things.things",
10.
One. "Key": {
12.
"_ID": 1
14.
15.},
16.
"V": 0
18.
19.},
20.
21. {
22.
"_id": ObjectId ("4e244382cac1e3490b9033d0
24.
"NS": "Things.things",
26.
"Key": {
28.
"J": 1
30.
31.},
32.
"Name": "J_1",
34.
"V": 0
36.
37.}
38.
39.]
Can return all indexes in the current database via Db.system.indexes.find ()
1. > Db.system.indexes.find ()
2.
3. {"Name": "_id_", "ns": "Things.things", "key": {"_id": 1}, "V": 0}
4.
5. {"_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 index is created on the _id field by default, and this particular index cannot be deleted. The _id field is mandatory only and is maintained by the database.
Nested keywords
In MongoDB, you can even index on an embedded document (embedded).
1. > Db.things.ensureIndex ({"Address.city": 1})
Document as Index
Any type, including documents (document), can be indexed:
1. > Db.factories.insert ({name: "xyz", Metro:{city: "New York", State: "NY"});
2.
3. > Db.factories.ensureIndex ({metro:1});
4.
5. > Db.factories.find ({metro:{city: "New York", State: "NY"});//able to query with index
6.
7. {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": <
8.
9. {"City": "New York", "state": "NY"}
10.
> Db.factories.find ({metro:{$gte: {city: "New York"}});//able to query with index
12.
{"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}
14.
> Db.factories.find ({metro:{state: "NY", City: "New York"}})//cannot return the result, the field is in the wrong order
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.
3. > db.factories.find ({"metro.city": "New York", "metro.state": "NY"});
4.
5. {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}
6.
7. > Db.factories.find ({"metro.city": "New York"});
8.
9. {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}
10.
> Db.factories.find (). Sort ({"metro.city": 1, "New York": 1});
12.
{"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}
14.
> Db.factories.find (). Sort ({"Metro.city": 1});
16.
{"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}
Combining keyword Indexes
In addition to the basic index of a single keyword, MongoDB also supports a combination of multiple keywords, which, like the basic Index, is a ensureindex () function that 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, which is important when sorting or scoping queries.
If you are building a composite index such as a,b,c, you can use an index query on A,a,b and A,b,c.
Sparse Index
Like sparse matrices, sparse indexes are indexed to documents that contain the fields being indexed.
Any sparse, missing document in one field will not be stored in the index, which is called a sparse index, which means that the value of the document with the missing field is lost.
The creation of sparse indexes is no different from the creation of a full index. When querying using sparse indexes, some document records that are missing a field may not be returned because the sparse index child returns the field being indexed. may be more difficult to understand, but look at a few examples is good to understand.
1. > Db.people.ensureIndex ({title:1},{sparse:true})//Set sparse index on Title field
2.
3. > Db.people.save ({name: "Jim"})
4.
5. > Db.people.save ({name: "Yang", title: "Prince"})
6.
7. > Db.people.find ();
8.
9. {"_id": ObjectId ("4e244dc5cac1e3490b9033d7"), "name": "Jim"}
10.
One. {"_id": ObjectId ("4e244debcac1e3490b9033d8"), "name": "Yang", "title": "Prince"}
12.
> Db.people.find (). Sort ({title:1})//Has records that contain indexed fields are returned
14.
{"_id": ObjectId ("4e244debcac1e3490b9033d8"), "name": "Yang", "title": "Prince"}
16.
> Db.people.dropIndex ({title:1})//After removing sparse indexes, all records are displayed
18.
{"Nindexeswas": 2, "OK": 1}
20.
> Db.people.find (). Sort ({title:1})
22.
{"_id": ObjectId ("4e244dc5cac1e3490b9033d7"), "name": "Jim"}
24.
{"_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 commands are as follows
1. > Db.things.ensureIndex ({firstname:1,lastname:1},{unique:true})
Missing keys
When a document is saved in a unique index to the collection, any missing indexed field is 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.
3. >db.things.save ({lastname: "Smith"});
4.
5. >db.things.save ({lastname: "Jones"})//will produce an error because FirstName will have two null.
Duplicate value:
A unique index cannot be created on a key with duplicate values, if you must create it on such a key, then think the system will save the first record and the remaining records will be deleted, just add the dropdups option when creating the index
1. >db.things.ensureindex ({firstname:1}, {unique:true, dropdups:true})
2.
3. Dropping Indexes
To delete an index on a specific collection:
1. >db.collection.dropindexes ();
To delete an index from a collection:
1. Db.collection.dropIndex ({x:1, Y:-1})
You can also perform a direct delete of the command
1. Db.runcommand ({dropindexes: ' foo ', index: {y:1}})//delete index of {y:1} in collection Foo
2.
3.//Remove All indexes:
4.
5. Db.runcommand ({dropindexes: ' foo ', Index: ' * '})//delete all indexes in collection foo
Rebuild Index:
You can rebuild the index with the following command:
1. Db.myCollection.reIndex ()
2.
3.//Same as:
4.
5. Db.runcommand ({reIndex: ' mycollection '})
This is usually unnecessary, but it is useful to rebuild the index when the collection is large in size 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 the update object is, it is updated only if the key on the index changes. has greatly 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 can be seen by running Db.system.indexes.find ().
The size of the indexed field has the largest limit and is currently close to bytes. It is possible to establish an index on a field that is greater than this value, but the field is not indexed, and this restriction may be removed in a later version.
Performance of indexes
Indexing allows data to be retrieved through key fields, enabling quick querying and updating of data.
However, it is important to note that indexes also add some burden to the system when inserting and deleting them. When inserting data into the collection, the indexed fields must be added to the B-tree, so the index is suitable for reading far more than the written dataset, and for frequently written collections, in some cases the index has side effects. But most collections are frequently read collections, so collections are useful in most cases.
Use sort () without indexing
If the data collection is relatively small (typically less than 4M), the data can be returned using sort () without having to establish an index. In this case, do the joint use of limit () and sort ().
About the creation and use of MongoDB index here, I hope to help you, your harvest will be my greatest happiness.

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.