1

I have a query that's something like the following

find( { a : { $gt: 3 } } ).sort( { b : -1 } )

Is it advised to create an index for field a and b separately?

Zaid Masud
  • 13,225
  • 9
  • 67
  • 88
tom
  • 14,273
  • 19
  • 65
  • 124

1 Answers1

3

No, with compound index query will work faster:

db.items.ensureIndex({a:1, b:-1});

Also you can make sure that your query use index with explain command.

Andrew Orsich
  • 52,935
  • 16
  • 139
  • 134
  • Thanks! When using Morphia, how could I define a compound index for a geo field and another field (a counter field)? Currently I have a @Indexed(value=IndexDirection.GEO2D) annotation for the geo field and a @Indexed(value=IndexDirection.DESC) for the other field? – tom Jan 30 '12 at 08:32
  • @tom: Create [compound index](http://www.mongodb.org/display/DOCS/Geospatial+Indexing#GeospatialIndexing-CompoundIndexes): `db.places.ensureIndex( { location : "2d" , counter : -1 } );` and make sure that it work with `explain` command. – Andrew Orsich Jan 30 '12 at 09:11