当前位置:网站首页>Mongodb index operation

Mongodb index operation

2022-06-24 10:47:00 Chen Bucheng I

One . brief introduction

The index of the database is similar to the directory index of the book , With the index , When you read a book, you don't have to look through the whole book , You can jump directly to the target content according to the number of directory pages , Improve reading and query efficiency . So is the index of the database , Its function is to improve the query speed , With the index ,MongoDB When querying, you can find entries in the index , Jump straight to the target collection The location of .

Two . Default index

When retrieving the system index , You can find ,mongodb By default, a default is established for each set ”_id” Indexes , The index used as a reference for retrieval . That is, our usual find All operations are based on the default ”_id” This index is used to find

> db.system.indexes.find();{ "v" : 1, "key" : { "_id" : 1 }, "ns" : "kaiye.c1", "name" : "_id_" }{ "v" : 1, "key" : { "_id" : 1 }, "ns" : "kaiye.c2", "name" : "_id_" }{ "v" : 1, "key" : { "_id" : 1 }, "ns" : "kaiye.c3", "name" : "_id_" }

3、 ... and . Why build a custom index

Gather first c4 Add a million pieces of data to , Post retrieval age=100 The data of , And call explain Function to calculate the information in the retrieval process , Found in no sort , Without a custom index , No data was queried , Need to scan onemillion pieces of data , And just a simple query costs 546 millisecond , This is difficult to accept in a business system with a large amount of data .

for(var i=0;i<1000000;i++){    db.c4.insert({name:"diao",age:i})}

Four . A comparison between the presence and absence of a custom index

First of all to c4 A collection of name Field indexing , Keyword is ensureIndex, The grammar is db.c4.ensureIndex({age:1}), Then execute the query age=100 The operation of , The retrieval information is shown in the figure below

Now you can see , For age After the fields are indexed, perform a simple query , At this time, the number of traversals is only one , And it takes almost 0, Compared with non indexed Retrieval , The effect is ordinary .

5、 ... and . Other operations on the index

1. Query information about the index db. aggregate .stats();

2. Delete index , Delete the collection , It will also delete all the indexes in the collection db. aggregate .dropIndex({ Index field :1})

3. Build unique index : A unique index means , When a field is set as a unique index , This field is in the set , The same value is not allowed , That is, the value is unique , For example, the above cases , Insert again age=100 A document of , There will be error messages . db. aggregate .ensureIndex({age:1},{unique:true})

原网站

版权声明
本文为[Chen Bucheng I]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/06/20210618155736700k.html