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:
- > 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.
- > Db.things.find ({j:2}); Query on indexed fields, faster
- {"_id": ObjectId ("4e24433dcac1e3490b9033be"), "X": 4, "J": 2}
- > Db.things.find ({x:3});//query on fields that are not indexed, you need to match fields on a per-field basis, slow
- {"_id": ObjectId ("4E244315CAC1E3490B9033BC"), "X": 3}
You can view all the indexes in the current collection by entering Getindexs () on the command line.
- > db.things.getIndexes ()
- [
- {
- "Name": "_id_",
- "NS": "Things.things",
- "Key": {
- "_ID": 1
- },
- "V": 0
- },
- {
- "_id": ObjectId ("4e244382cac1e3490b9033d0
- "NS": "Things.things",
- "Key": {
- "J": 1
- },
- "Name": "J_1",
- "V": 0
- }
- ]
Ability to return all indexes in the current database via Db.system.indexes.find ()
- > Db.system.indexes.find ()
- {"Name": "_id_", "ns": "Things.things", "key": {"_id": 1}, "V": 0}
- {"_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).
- > Db.things.ensureIndex ({"Address.city": 1})
Document as Index
Any type, including document, can be indexed:
- > Db.factories.insert ({name: "xyz", Metro:{city: "New York", State: "NY"});
- > Db.factories.ensureIndex ({metro:1});
- > Db.factories.find ({metro:{city: "New York", State: "NY"});//ability to query by index
- {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": <
- {"City": "New York", "state": "NY"}}
- > Db.factories.find ({metro:{$gte: {city: "New York"}});//ability to query by index
- {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}
- > 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:
- > Db.factories.ensureIndex ({"metro.city": 1, "Metro.state": 1})
- > Db.factories.find ({"metro.city": "New York", "metro.state": "NY"});
- {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}
- > Db.factories.find ({"metro.city": "New York"});
- {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}
- > Db.factories.find (). Sort ({"metro.city": 1, "New York": 1});
- {"_id": ObjectId ("4e244744cac1e3490b9033d2"), "name": "XYZ", "Metro": {"City": "New York", "state": "NY"}}
- > Db.factories.find (). Sort ({"Metro.city": 1});
- {"_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.
- > 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.
- > Db.people.ensureIndex ({title:1},{sparse:true})//Create a sparse index on the title field
- > Db.people.save ({name: "Jim"})
- > Db.people.save ({name: "Yang", title: "Prince"})
- > Db.people.find ();
- {"_id": ObjectId ("4e244dc5cac1e3490b9033d7"), "name": "Jim"}
- {"_id": ObjectId ("4e244debcac1e3490b9033d8"), "name": "Yang", "title": "Prince"}
- > Db.people.find (). Sort ({title:1})//The record containing the indexed field is returned
- {"_id": ObjectId ("4e244debcac1e3490b9033d8"), "name": "Yang", "title": "Prince"}
- > Db.people.dropIndex ({title:1})//After deleting the sparse index, all records are displayed
- {"Nindexeswas": 2, "OK": 1}
- > Db.people.find (). Sort ({title:1})
- {"_id": ObjectId ("4e244dc5cac1e3490b9033d7"), "name": "Jim"}
- {"_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
- > 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:
- >db.things.ensureindex ({firstname:1}, {unique:true});
- >db.things.save ({lastname: "Smith"});
- >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
- >db.things.ensureindex ({firstname:1}, {unique:true, dropdups:true})
- Dropping Indexes
To delete an index on a specific collection:
- >db.collection.dropindexes ();
To delete an index in a collection:
- Db.collection.dropIndex ({x:1, Y:-1})
You can also perform command-in-the-go removal directly
- Db.runcommand ({dropindexes: ' foo ', index: {y:1}})//delete index of {y:1} in set foo
- Remove all indexes:
- Db.runcommand ({dropindexes: ' foo ', Index: ' * '})//delete all indexes in the set foo
Rebuild Index:
You can rebuild the index with the following command:
- Db.myCollection.reIndex ()
- Same as:
- 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