当前位置:网站首页>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
- About stack area, heap area, global area, text constant area and program code area
- 虚拟人产业面临的挑战
- Huawei Nova 10 series released Huawei application market to build a solid application security firewall
- 质量体系建设之路的分分合合
- Implementation rules for archiving assessment materials of robot related courses 2022 version
- Logo special training camp section 1 Identification logo and logo design ideas
- Google Earth Engine(GEE)——基于 MCD64A1 的 GlobFire 日常火灾数据集
- How diff are the contents of the same configuration item in different environments?
- 我在linux里面 通过调用odspcmd 查询数据库信息 怎么静默输出 就是只输出值 不要这个
猜你喜欢

SPSS installation and activation tutorial (including network disk link)

NFT insider 64: e-commerce giant eBay submitted an NFT related trademark application, and KPMG will invest $30million in Web3 and metauniverse

Locust性能测试 —— 环境搭建及使用

Common open source codeless testing tools

A large number of virtual anchors in station B were collectively forced to refund: revenue evaporated, but they still owe station B; Jobs was posthumously awarded the U.S. presidential medal of freedo

30余家机构联合发起数字藏品行业倡议,未来会如何前进?

LOGO special training camp section I identification logo and Logo Design Ideas

新版判断PC和手机端代码,手机端跳转手机端,PC跳转PC端最新有效代码

Use blocconsumer to build responsive components and monitor status at the same time

Business is too busy. Is there really no reason to have time for automation?
随机推荐
MySQL storage data encryption
Naacl-22 | introduce the setting of migration learning on the prompt based text generation task
虚拟人产业面临的挑战
Microservices -- Opening
Why is Dameng data called the "first share" of domestic databases?
idea中pom.xml依赖无法导入
PostgreSQL JOIN实践及原理
特征缩放 标准化 归一化
Ascendex launched Walken (WLKN) - an excellent and leading "walk to earn" game
【OpenGL】笔记二十九、抗锯齿(MSAA)
Solana chain application crema was shut down due to hacker attacks
leetcode 72. Edit distance edit distance (medium)
The table is backed up in ODPs. Why check m in the metabase_ Table, the logical sizes of the two tables are inconsistent, but the number of
[the 2023 autumn recruitment of MIHA tour] open [the only exclusive internal push code of school recruitment eytuc]
Implementation rules for archiving assessment materials of robot related courses 2022 version
Convolutional neural network model -- lenet network structure and code implementation
集群的概述与定义,一看就会
Practice and principle of PostgreSQL join
About stack area, heap area, global area, text constant area and program code area
How diff are the contents of the same configuration item in different environments?