Home > Backend Development > PHP Tutorial > Some notes on Mongo indexes

Some notes on Mongo indexes

不言
Release: 2023-04-02 21:44:02
Original
1871 people have browsed it

This article mainly introduces some instructions about Mongo index, which has certain reference value. Now I share it with you. Friends in need can refer to it

Index usage scenarios

Advantages: Speed ​​up the query

Disadvantages: Additions, deletions and modifications will cause additional overhead and occupy space

tips: Return more than half of the data in the collection, and the full table scan is more efficient

Index basics

Basic operations

View index: db.test.getIndexes()

Create index: db.test.ensureIndex({" username":1},{"background":true,"name":"index_test_name"}) //When there is a large amount of data, it can be executed in the background without blocking

Delete the index: db.test.dropIndex({ "username":1})

View the index size: db.test.totalIndexSize()

Attribute

Index order:

1 is positive order, -1 is reverse order

In the composite index, you need to pay attention to the order (id:1, age:-1)

Index attributes:

  • Uniqueness

db.test.ensureIndex({x:1,y:1},{unique:true})
Copy after login
  • Sparseness

db.test.ensureIndexx({},{sparse:true/false})
不稀疏(默认):
1. 可插入不存在索引字段的数据,null; 
2. 可筛选不存在字段: db.test.find({m:{$exist:ture}})
稀疏:
Copy after login

Optimization analysis method

  • explain

    Learn how the system handles requests

cursor  返回游标类型(BasicCursor或BtreeCursor)
nscanned  被扫描的文档数量
n 返回的文档数
millis  耗时(毫秒)
indexBounds  所使用的索引
Copy after login
  • hint

    Force the use of an index

db.test.find({"age":20}).hint({"name":1,"age":1}) // .hint(name_1_age_1)
Copy after login
  • profile

    Set the log level and record slow queries

##Tips

  1. Automatically adjust the order of query conditions

  2. Can hit the index for the prefix regular expression (/^z /)

  3. Create indexes for keys that require a large amount of sorting to avoid loading all data into memory

  4. $ne, $nin will not use indexes

Index type

  • _id index

  • Single key index

  • Multi-key index

  • Compound index

  • Expired index

  • Full-text index

  • Geographical Location Index

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to PHP Chinese website!

Related recommendations:

The above is the detailed content of Some notes on Mongo indexes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template