索引顺序和查询顺序必须匹配吗

索引顺序和查询顺序必须匹配吗

本文介绍了MongoDB:索引顺序和查询顺序必须匹配吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题涉及管理索引和搜索Bson Documents的内部方法.

This question concern the internal method to manage indexes and serching Bson Documents.

当您创建多个索引(例如"index1","index2","index3")时,该索引存储为在查询期间使用,但是查询的顺序和性能如何呢?

When you create a multiple indexes like "index1", "index2", "index3"...the index are stored to be used during queries, but what about the order of queries and the performance resulting.

样本
index1,index2,index3 ---->以相同顺序查询index1,index2,index3(最佳情况)index1,index2,index3 ---->以另一顺序查询index2,index1,index3(顺序已更改)

sample
index1,index2,index3----> query in the same order index1,index2,index3 (best case)index1,index2,index3----> query in another order index2,index1,index3 (the order altered)

很多时候,您使用嵌套查询,包括这3个索引以及其他项目或更多索引.查询的顺序将意味着浪费一些时间?是否必须传递符合定义的索引顺序的查询,或者内部体系结构必须注意此顺序搜索?我想知道我是否确实在意这一点,或者可以让我的查询变得更加自由.

Many times you use nested queries including these 3 index and others items or more indexes. The order of the queries would implicate some time lost?. Must passing the queries respecting the indexes order defined or the internal architecture take care about this order search? I searching to know if i do take care about this or can make my queries in freedom manier.

谢谢.

推荐答案

查询中条件的顺序不会影响它可以使用索引还是不使用索引.

The order of the conditions in your query does not affect whether it can use an index or no.

例如典型的文档结构:

e.g.typical document structure:

{
    "FieldA" : "A",
    "FieldB" : "B"
}

如果您在A和B上具有复合索引:

If you have an compound index on A and B :

db.MyCollection.ensureIndex({FieldA : 1, FieldB : 1})

然后以下两个查询将能够使用该索引:

Then both of the following queries will be able to use that index:

db.MyCollection.find({FieldA : "A", FieldB : "B"})
db.MyCollection.find({FieldB : "B", FieldA : "A"})

因此查询中条件的排序不会阻止索引的使用-我认为这是您要提出的问题.

So the ordering of the conditions in the query do not prevent the index being used - which I think is the question you are asking.

您可以通过在shell中尝试2个查询并在查找后添加.explain()来轻松地进行测试.我只是这样做来确认,他们都表明使用了复合索引.

You can easily test this out by trying the 2 queries in the shell and adding .explain() after the find. I just did this to confirm, and they both showed that the compound index was used.

但是,如果运行以下查询,则不会使用该索引,因为不会查询FieldA:

however, if you run the following query, this will NOT use the index as FieldA is not being queried on:

db.MyCollection.find({FieldB : "B"})

因此,是索引中的字段顺序决定了查询是否可以使用它,而不是查询本身中的字段顺序(这是卢卡斯所指的).

So it's the ordering of the fields in the index that defines whether it can be used by a query and not the ordering of the fields in the query itself (this was what Lucas was referring to).

这篇关于MongoDB:索引顺序和查询顺序必须匹配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 11:14