Why is this SORT stage here? Shouldn't it use the index instead?

I have an index that looks like this:

{a: 1, b: 1}

And my query looks something like this:

db.myCollection.find({a: {$regex : "^S"}}).sort({b:1})

When I do an “explain” on this plan, I’m seeing a SORT stage which means it’s using CPU and memory to do the sorting rather than using the order of the index. Is there a way to make this work?

The index {a:1,b:1} supports sorts on {a:1,b:1}, {a:1,b:-1}, {a:-1,b:1} and {a:-1,b-1}.

For example, in documents:


your query and sort wants


so while an IXSCAN can determine that _id:0 and _id:1 are in the result set, a SORT must determine the final order.


@Kevin_Rathgeber, was my post help you understand better. If it did, please mark my post as the solution. This will help keep this post useful and efficient. It is simply courtesy.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.