How does MongoDB treat find().sort() queries with respect to single and compound indexes?

安稳与你 提交于 2021-01-28 19:52:05

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/27739127/how-does-mongodb-treat-find-sort-queries-with-respect-to-single-and-compound

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!