Summary
In the previous article, a method for analyzing MongoDB performance was introduced, and this article will describe the use of indexes, which is also a common way of query optimization. Here's an introduction to the index if you create it.
Related articles
Getting started with [MongoDB]
[MongoDB] additions and deletions change
[Mongodb]count,gourp,distinct
[Mongodb]mapreduce
[MongoDB] Profiling Performance Analysis
[MongoDB] Index
Index
Index
We create an index for the name field above the collection of users
Db.users.ensureIndex ({"name":1})
Query the collection which indexes have been created above
Db.users.getIndexes ()
It was discovered through a query that the collection created an index for ID and name, where _id is the default index.
Delete the index above the field name
Db.users.dropIndex ({"name":1})
Composite Index
Create a composite index above name and age
Db.users.ensureIndex ({"name":1,"Age":-1 })
When the composite index is created, a query based on name and age will use that index, or a name-based query will use that index, but only the age-based query would not use the composite index.
Therefore, if you want to use a composite index, you must include the first n index columns in the composite index in the query criteria. However, if the order of key values in the query condition is inconsistent with the order of creation in the composite index, MongoDB can intelligently help us adjust that order so that the composite index can be used by the query.
Unique index
Indexes created by default are not unique indexes, if creating unique indexes requires the unique parameter set to True
Create a unique index for name
Db.users.ensureIndex ({"name":1},{"unique": True})
If the duplicate name value is inserted at this point, an error will be
Summarize
The creation, deletion, query, and unique creation of the index are described here.
[MongoDB] Index