Get the App
SLTechnology News&Howtos  ›  Database  › 

Mongodb query and Index Optimization

Shulou Source: shulou.com Published: 2022-06-01 13:32:30 09月14日 Update

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")

Tags: Index data query important price manufacturer document manufacturing same sparse success single button parameter only command field intensive suggestion efficiency data structure Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology OPPO Reno Shulou Information MariaDB NVidia