当前位置:网站首页>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 :
background
Boolean 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.
unique
Boolean type , Is the index created unique . Designated as true Create unique index . The default value is false.
name
Boolean type , Name of index . If not specified ,MongoDB Generates an index name by concatenating the field name of the index and the sort order .
dropDups
Boolean type , Whether to delete duplicate records when establishing a unique index , Appoint true Create unique index . The default value is false.
sparse
Boolean 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.
expireAfterSeconds
integer type , Specifies a value in seconds , complete TTL Set up , Sets the lifetime of the collection .
v
The version number of the index . The default index version depends on mongod The version that runs when the index is created .
weights
Index weight , Values in 1 To 99,999 Between , Represents the score weight of the index relative to other index fields .
default_language
Boolean 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_override
Boolean 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 .
边栏推荐
- 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
- LOGO特训营 第四节 字体设计的重要性
- Enabling digital economy Fuxin software attends the BRICs high level Forum on Sustainable Development
- Service online governance
- Common open source codeless testing tools
- Scala download and configuration
- Locust performance test - environment construction and use
- Redis的持久化机制
- MYSQL架构——用户权限与管理
- Use blocconsumer to build responsive components and monitor status at the same time
猜你喜欢
Introduction and application of bigfilter global transaction anti duplication component
Redis sentinel simply looks at the trade-offs between distributed high availability and consistency
Play with grpc - go deep into concepts and principles
It is said that software testing is very simple, but why are there so many dissuasions?
Business is too busy. Is there really no reason to have time for automation?
PMO: compare the sample efficiency of 25 molecular optimization methods
MYSQL架构——逻辑架构
Concurrent network modular reading notes transfer
串口数据帧
Unity-VScode-Emmylua配置报错解决
随机推荐
How to manage 15million employees easily?
LOGO特訓營 第一節 鑒別Logo與Logo設計思路
MD5 tool class
页面关闭前,如何发送一个可靠请求
2022-07-04:以下go语言代码输出什么?A:true;B:false;C:编译错误。 package main import “fmt“ func main() { fmt.Pri
Enabling digital economy Fuxin software attends the BRICs high level Forum on Sustainable Development
TLA+ 入门教程(1):形式化方法简介
Éducation à la transmission du savoir | Comment passer à un test logiciel pour l'un des postes les mieux rémunérés sur Internet? (joindre la Feuille de route pour l'apprentissage des tests logiciels)
SQL中MAX与GREATEST的区别
MySQL storage data encryption
常用的开源无代码测试工具
Use blocconsumer to build responsive components and monitor status at the same time
Jvm-Sandbox-Repeater的部署
NFT Insider #64:电商巨头eBay提交NFT相关商标申请,毕马威将在Web3和元宇宙中投入3000万美元
Flask 上下文详解
Tla+ introductory tutorial (1): introduction to formal methods
Common open source codeless testing tools
LOGO special training camp section I identification logo and Logo Design Ideas
How can the advertising system of large factories be upgraded without the presence of large models
质量体系建设之路的分分合合