当前位置:网站首页>[teacher Zhao Yuqiang] index in mongodb (Part 1)
[teacher Zhao Yuqiang] index in mongodb (Part 1)
2022-07-03 05:46:00 【Teacher zhaoyuqiang】

Index is the most effective way to improve query efficiency . Index is a special data structure , The index stores part of the data in a form that is easy to traverse ( Such as : A specific field or set of field values ), The index sorts the stored values according to certain rules , And the index is stored in memory , It's very fast to retrieve data from the index . If there is no index ,MongoDB Every document in the collection must be scanned , This kind of scanning is very inefficient , Especially when the amount of data is large .
One 、 The basics of indexing
Here's a relational database Oracle For example , Introduce the basic principle of index , As shown in the figure below :

It can be seen from the above picture that , The essence of an index is actually a table of contents for a book . When querying data in a table , Query directory first ( Indexes ) Line address in , Then query the data in the table through the row address , To improve query performance .
The figure below illustrates the MongoDB in , How indexes work in queries and sorts ?

Through this example , You can clearly see that the index stores a specific field or a collection of several fields , And sort them according to certain rules . When you create a collection ,MongoDB Automatically in _id Create a unique index on , Because it's unique , So it can prevent repetition _id Values are inserted into the collection . adopt getIndexes You can look it up MongoDB Index information on a set , As shown in the figure below .

When there is no index , By looking at the execution plan , You can see the query process , as follows : Inquire about :10 Department No , Wages less than 3000 Documents .

So how to create a simple index ? Attention from mongoDB 3.0 Start ensureIndex Abandoned , In the future, it's just db.collection.createIndex An alias for .

Now in deptno and sal Build an index on , And review the execution plan :db.emp.createIndex({“deptno”:1,“sal”:-1})

Be careful : Except that it can be used explain() Generate execution plan out of plan , There are also several optional parameters , as follows :
.explain(“allPlansExecution”)
.explain(“executionStats”)
.explain(“queryPlanner”)
Two 、 Index type one : Single key index (Single Field)
The single key index is the most common index , And _id Different indexes , Single key indexes are not automatically created .
Prepare the data :
db.testindex1.insert({"_id":1,"zipcode":1034,"location":{state:"NY",city:"New York"}})
Create a single key index on a single column :
db.testindex1.createIndex({"zipcode":1})
Create a single key index on nested Columns
db.testindex1.createIndex({"location:state":1})
Create a single key index on an embedded document
db.testindex1.createIndex({"location":-1})
This will put location As a whole .
3、 ... and 、 Index type two : Multi key index (Multikey Index)
A multi key index is created in the same way as a single key index , The difference is the value of the field . Value has multiple records , Such as arrays .

Pictured above , Create a multi key index based on an array on a collection , And the array is an embedded document .
Prepare the data :
db.testindex2.insertMany([
{ _id: 5, type: "food", item: "aaa", ratings: [ 5, 8, 9 ] },
{ _id: 6, type: "food", item: "bbb", ratings: [ 5, 9 ] },
{ _id: 7, type: "food", item: "ccc", ratings: [ 9, 5, 8 ] },
{ _id: 8, type: "food", item: "ddd", ratings: [ 9, 5 ] },
{ _id: 9, type: "food", item: "eee", ratings: [ 5, 9, 5 ] }])
Based on ratings Column creates a multi key index :
db.testindex2.createIndex( { ratings: 1 } )
Query array for 5,9 Documents
db.testindex2.find( { ratings: [ 5, 9 ] } )
Here's the execution plan
db.testindex2.find( { ratings: [ 5, 9 ] } ).explain()
边栏推荐
- [set theory] relational closure (relational closure related theorem)
- "C and pointer" - Chapter 13 advanced pointer int * (* (* (*f) () [6]) ()
- Win10 install pytullet and test
- Introduction to redis using Lua script
- Export the altaro event log to a text file
- JS implements the problem of closing the current child window and refreshing the parent window
- Pytorch through load_ state_ Dict load weight
- Source insight operation manual installation trial
- Notepad++ wrap by specified character
- Method of finding prime number
猜你喜欢

今天很多 CTO 都是被幹掉的,因為他沒有成就業務

3dslam with 16 line lidar and octomap

Final review (Day5)

6.23 warehouse operation on Thursday

Apache+PHP+MySQL环境搭建超详细!!!

redis 无法远程连接问题。

Hotel public broadcasting background music - Design of hotel IP network broadcasting system based on Internet +

大二困局(复盘)

kubernetes资源对象介绍及常用命令(五)-(ConfigMap)

【一起上水硕系列】Day 7 内容+Day8
随机推荐
Final review (day3)
How to set up altaro offsite server for replication
Pytorch through load_ state_ Dict load weight
[function explanation (Part 1)] | | knowledge sorting + code analysis + graphic interpretation
Together, Shangshui Shuo series] day 9
Primary school campus IP network broadcasting - Design of primary school IP digital broadcasting system based on campus LAN
[written examination question analysis] | | get [sizeof and strlen] [pointer and array] graphic explanation + code analysis
Apache+php+mysql environment construction is super detailed!!!
Altaro VM backup getting started
[minesweeping of two-dimensional array application] | [simple version] [detailed steps + code]
AtCoder Beginner Contest 258(A-D)
Final review (Day2)
期末复习(DAY7)
QT read write excel -- qxlsx insert chart 5
CAD插件的安裝和自動加載dll、arx
[untitled]
DEX net 2.0 for crawl detection
Final review (Day5)
Altaro virtual machine replication failed: "unsupported file type vmgs"
redis 遇到 NOAUTH Authentication required

