Indexing is the most effective means of improving query query efficiency. An index is a special data structure that stores portions of the data in an easy-to-traverse format (for example, a specific field or set of field values), which sorts the stored values by a certain rule, and where the index is stored in memory, where the data retrieved from the index is very fast. Without an index, MONGODB must scan every document in the collection, which is very inefficient, especially when the amount of data is large.
1. View the index:
Db. Collection_name.getindexes ()
[
{
"V": 1,
"key": {
"_id": 1
},
"name": "_id_",
"ns": "Mars". Collection_name "
}
]
2. Create an index:
The number 1 means that it is stored in ascending index, 1 means that it is stored in descending order by index
1). Create a single index
Db. Collection_name.ensureindex ({name:1})
[
{
"V": 1,
"key": {
"_id": 1
},
"name": "_id_",
"ns": "Mars". Collection_name "
},
{
" V ": 1,
" key ": {
" name ": 1
},
" name ":" Name_1 ",
" ns " : "Mars. Collection_name "
}
]
2). Create a composite index
Db. Collection_name.ensureindex ({name:1,age:1})
[
{
"V": 1,
"key": {
"_id": 1
},
"name": "_id_",
"ns": "Mars". Collection_name "
},
{
" V ": 1,
" key ": {
" name ": 1
},
" name ":" Name_1 ",
" ns ":" Mars. Collection_name "
},
{
" V ": 1,
" key ": {
" name ": 1,
" age ": 1
},
" name ":" Name " _1_age_1 ",
" ns ":" Mars. Collection_name "
}
]
3). Create a unique index:
Db. Collection_name.ensureindex ({name:1,age:1},{unique:true})
[
{
"V": 1,
"key": {
"_id": 1
},
"name": "_id_",
"ns": "Mars". Collection_name "
},
{
" V ": 1,
" unique ": true,
" key ": {
" NAME ": 1,
" age ": 1
},
"name": "Name_1_age_1",
"ns": "Mars." Collection_name "
}
]
3. Delete the index:
1). Deletes the second index
DB as shown above, as indicated on the Index name field name. Collection_name.dropindex ("Name_1_age_1_unique_true")
2). Deletes the key based on the index specified at creation time, such as deleting the second index
DB as shown above. Collection_name.dropindex ({name:1,age:1})
3). Delete all indexes
db. Collection_name.dropindexes ()