当前位置:网站首页>[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()
边栏推荐
- C 语言文件操作函数大全 (超详细)
- Pytorch through load_ state_ Dict load weight
- Configure and use Anaconda environment in pycharm
- Crontab command usage
- Common exceptions when Jenkins is released (continuous update...)
- Transferring images using flask
- [trivia of two-dimensional array application] | [simple version] [detailed steps + code]
- Introduction to redis using Lua script
- Calculation method of AUC
- Download the corresponding version of chromedriver
猜你喜欢
![[advanced pointer (1)] | detailed explanation of character pointer, pointer array, array pointer](/img/9e/a4558e8e53c9655cbc1a38e8c0536e.jpg)
[advanced pointer (1)] | detailed explanation of character pointer, pointer array, array pointer

一起上水硕系列】Day 9

Latest version of source insight

配置xml文件的dtd

Qt读写Excel--QXlsx插入图表5

Simpleitk learning notes

Strategy pattern: encapsulate changes and respond flexibly to changes in requirements
![Ensemble, série shuishu] jour 9](/img/39/c1ba1bac82b0ed110f36423263ffd0.png)
Ensemble, série shuishu] jour 9

6.23 warehouse operation on Thursday
![[escape character] [full of dry goods] super detailed explanation + code illustration!](/img/33/ec5a5e11bfd43f53f2767a9a0f0cc9.jpg)
[escape character] [full of dry goods] super detailed explanation + code illustration!
随机推荐
配置xml文件的dtd
Notepad++ wrap by specified character
Primary school campus IP network broadcasting - Design of primary school IP digital broadcasting system based on campus LAN
PHP笔记超详细!!!
redis 遇到 NOAUTH Authentication required
2022.DAY592
Apache+php+mysql environment construction is super detailed!!!
Talk about how to use p6spy for SQL monitoring
2022.7.2day594
SimpleITK学习笔记
【无标题】
Map的扩容机制
Linux登录MySQL出现ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)
Azure file synchronization of altaro: the end of traditional file servers?
Explanation of variables, code blocks, constructors, static variables and initialization execution sequence of static code blocks of Ali interview questions
期末复习(DAY6)
Obtenir et surveiller les journaux du serveur distant
Today, many CTOs were killed because they didn't achieve business
@Autowired 导致空指针报错 解决方式
2022.DAY592

