Indexes can significantly improve query performance. Consider the query types used in your application so that you can define related indexes. Once the index definition is complete, it is very easy to create them in mongodb.
Mongodb indexes are similar in concept to those of MySQL and other relational databases. When you need to create an index in MySQL in some situations, this situation also applies to Mongodb.
Basic Concepts
An index is a data structure that collects the values of specified fields in the documents in the collection. This data structure is used by the Mongo query optimizer to quickly classify and sort documents in a collection. Formally speaking, these indexes are implemented in the form of "B-Tree" indexes.
In shell, you can call ensureIndex () to create an index. The parameter is a document that specifies one or more keywords. Refer to the example in the previous mongo usage basic knowledge. We can index the "j" field as follows:
db.things.ensureIndex({j:1});
The ensureIndex () function creates an index only when the index does not exist.
Once an index is created for a field in the Set, the random query speed for this field will be very fast. Without this index, mongodb needs to traverse all documents to match the fields in the query:
db.things.find({j:2}); // fast - uses index
db.things.find({x:3}); // slow - has to check all because 'x' isn't indexed
View the existing indexes in the Set in shell. You can run the following command:
db.things.getIndexes()
To view all the indexes in the database, run:
db.system.indexes.find()
Create Option
The second parameter of the ensureIndex function is the document/object carrying the creation option. These options include:
Option |
Value |
Default Value |
Background |
True/false |
False |
DropDups |
True/false |
False |
Unique |
True/false |
False |
Sparse |
True/false |
False |
V |
Index version. 0 = earlier than v2.0, 1 = smaller/faster (current) |
1 in v2.0. unless in special situations, 1 is used by default. |