mongo index

This article mainly introduces the index of mongo

  • The role of the index
  • type of index
  • Indexing Considerations
  • Index creation and management

The role of the index
The function of the index is to query the index first. If the corresponding content is found in the index, then the corresponding data can be found according to the address corresponding to the index, thereby speeding up the query. However, each time an insert operation is performed, the B-tree corresponding to the index is updated. So you need to create indexes as needed, don't create unnecessary indexes.

type of index
  • single key index
  • compound index
  • unique index
  • sparse index


Notes on Index Creation
1. If the collections are not very large, it is not recommended to build an index, because this will cause two searches for each query, one is to search the index, and the other is to search the table.
2. If an index is an index used by administrators to maintain data, it is best not to create it. When indexing, it is best to create indexes for some of the queries that are already used in the program.

view index
db.COLLECTION.getIndexKeys();
db.COLLECTION.getIndices();

create index
>db.user.ensureIndex({"name":1})

{
"createdCollectionAutomatically" : false,
"numberIndexesBefore": 1,
"numIndexesAfter": 2,
"ok" : 1
}

> db.user.getIndexKeys();
[ { "_id" : 1 }, { "name" : 1 } ]

Create a composite index
db.user.ensureIndex({"name":1,"age":1})


rebuild index
> db.user.reIndex({"name":1});
{
"nIndexesWas" : 2,
"nIndexes" : 2,
"indexes" : [
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "xytest.user"
},
{
"v" : 2,
"key" : {
"name" : 1
},
"name" : "name_1",
"ns" : "xytest.user"
}
],
"ok" : 1
}


删除索引
db.dropIndex("name_1")

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325641150&siteId=291194637