当前位置:网站首页>Summary of index operations in mongodb
Summary of index operations in mongodb
2022-07-04 22:37:00 【cui_ yonghua】
One . summary
Indexes can often make queries more efficient , If there is no index ,MongoDB When the data is read, each file in the collection must be scanned and those records that meet the query criteria must be selected . The query efficiency of scanning the whole collection is very low , Especially when dealing with large amounts of data , Queries can take tens of seconds or even minutes , This can be deadly to the performance of your site .
An index is a special data structure , The index is stored in a collection of data that is easy to read through , An index is a structure that sorts the values of a column or columns in a database table
Indexes (Index) Help MySQL Data structure for efficient data acquisition .
You can get the essence of the index : An index is a data structure .
It can be simply understood as “ Quickly find data structures in order ”.
An index stores the values of a particular field or group of fields , Sort by the value of this field . Sorting of index entries supports effective equality matching and range based query operations .
in addition ,MongoDB You can return the sorted results by using the order in the index .
Index principle :MongoDB The data structure of the index defaults to B-Tree.B-Tree Characteristics of index structure of type :
- The depth of each leaf node is the same , Usually it is 3 Layer or 4 layer ;
- Query operation , Performance is very objective ;
- For range queries , Directly traversing the linked list of leaf nodes can quickly locate the pointer position matching the document record .
Official documents - Indexes :https://www.mongodb.com/docs/manual/indexes/
Two . Common operations of indexing
2.1 Create index
MongoDB Use createIndex() Method to create the index .( 3.0.0 Add... After version )
Grammar format :db.collection.createIndex(keys, options)
In the syntax Key The value is the index field that you want to create ,1 Creates an index in ascending order for the specified , If you want to create the index in descending order specify as -1 that will do .
The optional parameters are as follows :
backgroundBoolean type , The indexing process blocks other database operations ,background You can specify backchannel mode to create indexes , That is, increase “background” Optional parameters . “background” The default value is false.
uniqueBoolean type , Is the index created unique . Designated as true Create unique index . The default value is false.
nameBoolean type , Name of index . If not specified ,MongoDB Generates an index name by concatenating the field name of the index and the sort order .
dropDupsBoolean type , Whether to delete duplicate records when establishing a unique index , Appoint true Create unique index . The default value is false.
sparseBoolean type , Indexes are not enabled for field data that does not exist in the document ; This parameter requires special attention , If set to true Words , Documents that do not contain corresponding fields are not queried in index fields .. The default value is false.
expireAfterSecondsinteger type , Specifies a value in seconds , complete TTL Set up , Sets the lifetime of the collection .
vThe version number of the index . The default index version depends on mongod The version that runs when the index is created .
weightsIndex weight , Values in 1 To 99,999 Between , Represents the score weight of the index relative to other index fields .
default_languageBoolean type , For text index , This parameter determines the list of stop words and the rules for the word stem and lexicon . Default to English
language_overrideBoolean type , For text index , This parameter specifies the name of the field to be included in the document , The language overrides the default language, The default value is language.
Case study 1: Create index
db.col.createIndex({
"title":1})
Case study 2:createIndex() Method you can also set up multiple fields to create an index ( A relational database is called a composite index ).
db.col.createIndex({
"title":1,"description":-1})
Case study 3: Create indexes in the background
db.values.createIndex({
open: 1, close: 1}, {
background: true})
notes :MongoDB You can also use ensureIndex() Method to create the index , 3.0.0 It can also be used after version , But only createIndex() Another name for .
2.2 Commonly used instructions
1、 Look at the collection index :db.col.getIndexes()
2、 Look at the size of the set index :db.col.totalIndexSize()
3、 Delete all indexes of the collection :db.col.dropIndexes()
4、 Deletes the specified index of the collection :db.col.dropIndex(" The index name ")
5、 utilize TTL Set the expiration time of the stored data : Expires after a specified period of time or at a specified point in time ,MongoDB Independent thread to clear data . This is similar to setting the scheduled automatic deletion of tasks , You can clear preconditions such as history or logs , Set up Index The key field of is date type new Date().
Case study : For example, in the data record createDate When the date type is :① Setup time 180 Automatically clear after seconds ;② Set after the record is created ,180 Seconds or so to delete .
db.col.createIndex({"createDate": 1},{expireAfterSeconds: 180})
3、 ... and 、 Index limits
3.1、 Maximum range
The index in the collection cannot exceed 64 individual
The index name cannot be longer than 125 Characters
A composite index can have at most 31 A field
3.2、 Query restrictions
The index cannot be used by the following query :
- Regular expressions and non operators , Such as $nin, $not, etc. .
- Arithmetic operator , Such as $mod, etc. .
- $where Clause
therefore , It is a good habit to detect whether the statement uses an index , It can be used explain Check it out. .
3.3、 Extra expenses
Using indexes comes at a price , For each index added , Every write operation ( Insert 、 to update 、 Delete ) Will take more time . This is because , When the data changes ,MongoDB Not only to update the document , Also update all indexes on the collection . therefore , If you rarely read a collection , Index is not recommended .
边栏推荐
- How to reset the password of MySQL root account
- Common open source codeless testing tools
- 2022-07-04: what is the output of the following go language code? A:true; B:false; C: Compilation error. package main import “fmt“ func main() { fmt.Pri
- 醒悟的日子,我是怎么一步一步走向软件测试的道路
- 国产数据库乱象
- NFT Insider #64:电商巨头eBay提交NFT相关商标申请,毕马威将在Web3和元宇宙中投入3000万美元
- UML图记忆技巧
- Introduction and application of bigfilter global transaction anti duplication component
- 记录:关于Win10系统中Microsoft Edge上的网页如何滚动截屏?
- 微服务--开篇
猜你喜欢

Scala下载和配置

Close system call analysis - Performance Optimization

MYSQL架构——逻辑架构

Li Kou 98: verify binary search tree

Unity修仙手游 | lua动态滑动功能(3种源码具体实现)

NFT Insider #64:电商巨头eBay提交NFT相关商标申请,毕马威将在Web3和元宇宙中投入3000万美元

堆排序代码详解

Nat. Commun.| Machine learning jointly optimizes the affinity and specificity of mutagenic therapeutic antibodies

LOGO特训营 第一节 鉴别Logo与Logo设计思路

AscendEX 上线 Walken (WLKN) - 一款卓越领先的“Walk-to-Earn”游戏
随机推荐
Business is too busy. Is there really no reason to have time for automation?
Short video system source code, click the blank space of the screen, the keyboard does not automatically stow
Logo special training camp section III initial creative techniques
[Yugong series] go teaching course 003-ide installation and basic use in July 2022
SPSS安装激活教程(包含网盘链接)
Scala download and configuration
[the 2023 autumn recruitment of MIHA tour] open [the only exclusive internal push code of school recruitment eytuc]
2022-07-04: what is the output of the following go language code? A:true; B:false; C: Compilation error. package main import “fmt“ func main() { fmt.Pri
leetcode 72. Edit distance edit distance (medium)
Deployment of JVM sandbox repeater
如何实现轻松管理1500万员工?
Domestic database chaos
蓝队攻防演练中的三段作战
Why is Dameng data called the "first share" of domestic databases?
Prosperity is exhausted, things are right and people are wrong: where should personal webmasters go
Tla+ introductory tutorial (1): introduction to formal methods
Shell script implements application service log warehousing MySQL
Enabling digital economy Fuxin software attends the BRICs high level Forum on Sustainable Development
Unity-VScode-Emmylua配置报错解决
LOGO special training camp section I identification logo and Logo Design Ideas