且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MongoDB如何处理关于单索引和复合索引的find().sort()查询?

更新时间:2023-11-14 08:21:22

如果我明白你的意思,这可能会有所帮助:

假设您有这些文档作为样本

  {栏位1:1栏位2:2},{栏位1:2栏位2:3,},{栏位1:1栏位2:4} 

第1步:您仅具有 filed1 的索引(索引的名称为 field1_1 )):执行: db.test3.find({field1:1}).sort({field2:1})

mongo使用 field1_1 索引搜索文档..explain()的结果是:

 "cursor":"BtreeCursor field1_1","isMultiKey":否,"n":2"nscannedObjects":2"nscanned":2 

第2步:添加复合索引,将其命名为 field1_1_field2_1 ,现在您为字段1设置了2个索引.

执行 find().sort()查询,您将拥有

 "cursor":"BtreeCursor field1_1_field2_1","isMultiKey":否,"n":2"nscannedObjects":2"nscanned":2 

凝聚力:

如果您使用 db.test3.find({field1:1}).sort({field2:1}),则mongo将使用 field1_1_field2_1 索引./p>

如果您使用 db.test3.find({field1:1}),则mongo将使用 field1_1 索引.

您的情况是,如果您只有 field1_1_field2_1 索引并且正在执行 db.test3.find({field1:1}),则mongo将使用 field1_1_field2_1 索引.

So I have a typical find().sort() query that I run on my mongo collection.

db.collection.find({field1:1}).sort({field2:1})

Now, say I have three indexes on this collection:

  1. single index on field1
  2. single index on field2
  3. compound index on field1 and field2 - {field1:1,field2:1}

Now my question, how does mongoDB treat the above query? What are the indexes that will be used in a query like that- two single indexes or the one compound index?

If I remove the compound index, does it in fact make use of the two single indexes but slowing down?

If I got your point, this might help:

Assuming you have these documents for sample

{
    field1 : 1,
    field2 : 2,
},
{
    field1 : 2,
    field2 : 3,
},
{
    field1 : 1,
    field2 : 4,
}

Step 1: you have index just for filed1 (name of index field1_1)}: perform the : db.test3.find({field1:1}).sort({field2:1})

the mongo uses field1_1 index to search in document. the result of .explain() is:

"cursor" : "BtreeCursor field1_1",
"isMultiKey" : false,
"n" : 2,
"nscannedObjects" : 2,
"nscanned" : 2,

Step 2: add your compound index, name it field1_1_field2_1, now you have 2 index for field 1.

perform find().sort() query, you will have

"cursor" : "BtreeCursor field1_1_field2_1",
"isMultiKey" : false,
"n" : 2,
"nscannedObjects" : 2,
"nscanned" : 2,

Concolusion:

if you use db.test3.find({field1:1}).sort({field2:1}), the mongo will use field1_1_field2_1 index.

if you use db.test3.find({field1:1}), the mongo will use field1_1 index.

I your case, If you have just field1_1_field2_1 index and you are performing db.test3.find({field1:1}), the mongo will use field1_1_field2_1 index as well.