当前位置:网站首页>[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()
边栏推荐
- 2022.DAY592
- mapbox尝鲜值之云图动画
- Training method of grasping angle in grasping detection
- JS implements the problem of closing the current child window and refreshing the parent window
- 今天很多 CTO 都是被干掉的,因为他没有成就业务
- Common exceptions when Jenkins is released (continuous update...)
- 请求数据库报错:“could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGram
- 配置xml文件的dtd
- Redis encountered noauth authentication required
- Progressive multi grasp detection using grasp path for rgbd images
猜你喜欢

Gan network thought

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

3dslam with 16 line lidar and octomap

Exception when introducing redistemplate: noclassdeffounderror: com/fasterxml/jackson/core/jsonprocessingexception

6.23星期四库作业

Classification and discussion of plane grab detection methods based on learning

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

Why should we rewrite hashcode when we rewrite the equals method?

"C and pointer" - Chapter 13 function pointer 1: callback function 2 (combined with template to simplify code)

MySQL 5.7.32-winx64 installation tutorial (support installing multiple MySQL services on one host)
随机推荐
Crontab command usage
Btrfs and ext4 - features, strengths and weaknesses
[trivia of two-dimensional array application] | [simple version] [detailed steps + code]
Life is a process of continuous learning
Hotel public broadcasting background music - Design of hotel IP network broadcasting system based on Internet +
Why should we rewrite hashcode when we rewrite the equals method?
How to install and configure altaro VM backup for VMware vSphere
Obtenir et surveiller les journaux du serveur distant
How do I migrate my altaro VM backup configuration to another machine?
CAD插件的安装和自动加载dll、arx
redis 遇到 NOAUTH Authentication required
Qt读写Excel--QXlsx插入图表5
Training method of grasping angle in grasping detection
Ext4 vs XFS -- which file system should you use
[untitled]
Can altaro back up Microsoft teams?
Altaro o365 total backup subscription plan
2022.6.30DAY591
Calculation method of AUC
[escape character] [full of dry goods] super detailed explanation + code illustration!

