Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Mongodb query and Index Optimization

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Index:

Query statement:

Db.products.find ({

"details.manufacturer": "acme"

"pricing.sale": {

$lt: 7500

}

})

Single key index:

Manufacturer (manufacturer) and price (price)

Composite index:

Manufacturer (manufacturer) and price (price)

The order of the composite index is important!

The existence of the index makes the write operation a little less efficient. Therefore, only the fields that will be used will be indexed!

Most indexes of mongodb use B-tree data structure.

Unique index:

Db.users.createIndex ({"account": 1}, {"unique": true})

(if the same account is inserted, an exception will be reported. It is recommended that you create an index before creating the data to constrain the data)

If the data is not important, you can delete the duplicate key document and use the dropDups parameter:

Db.users.createIndex ({account: 1}, {unique: true, dropDups: true})

Sparse index:

The index is intensive by default.

Explain:

You can use this command to figure out how mongodb executes the query

Db.the_table.find ({"age": {"$gte": 0}}) .explain ("executionStats")

TotalKeysExamined shows that the index number of the entire scan is 0, and docsExamined shows 9 documents that scan the entire collection.

You can create an index with ensureIndex () or createIndex (), where the old version uses ensureIndex ()

The getIndexes () method checks whether the index is created successfully:

(the collection now has two indexes: the first is the standard _ id index; the second is the num index we created. The index names are _ id_ and num_1, respectively)

After setting the index, viewing with explain will change:

Db.numbers.find ({num: {"$gt": 19995}}) .explain ("executionStats")

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report