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?

2
  • 1
    very helpful: docs.mongodb.org/manual/tutorial/sort-results-with-indexes Commented Jan 2, 2015 at 8:00
  • @Disposer so it uses a compound index right...is it correct to expect the query to use the single indexes and to get slow if there's no compound index? Commented Jan 2, 2015 at 8:08

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Which is a perfect description why it does not make sense to have single field indices in case the field already is indexed in a compound index.
@MarkusWMahlberg true, though I was more concerned with not having a compound index :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.