Sorting on compound Indexes This may be a novice question but could it be possible query here.

If I have a compound Index as 

{ a: 1, b: 1, c: 1, d: 1 }

Is this query possible?

db.data.find( { a: {$gte:1,$lt:2}, b: { $gt: 3} },c:"test",d:"yes" ).sort( { b: 1 } )


I mean can I use sorting on field b with this compound index and the specified query or do I need to create a separate index on b?
Compound indexes are great for static values

Flip the WHERE components so that static values are first

db.data.find( { c:"test", d:"yes", a: {$gte:1,$lt:2}, b: {$gt: 3} }).sort( { b: 1 } )


Create a different compound index

db.data.ensureIndex({c:1},{d:1},{b:1},{a:1})


How does it help ?


Static c value
Static d value
Sorted Range on b


One more thing

{$gte:1,$lt:2} is really {$eq:1}

I have discussed covering indexes and how the order of columns can changes things. In these posts, I talked about it from the MySQL perspective:


Apr 11, 2014 : Why is MySQL not using the index with the higher cardinality?
Aug 11, 2013 : How to index for a query with independent range conditions?
Nov 13, 2012 : Must an index cover all selected columns for it to be used for ORDER BY?