Syntax to MongoDB can use a compound index to return sorted results in query??

17 views
Skip to first unread message

easy_010481

unread,
Sep 17, 2012, 5:50:12 AM9/17/12
to mongod...@googlegroups.com
i read document and see the tip to use compound index to improve my query

In general, MongoDB can use a compound index to return sorted results if:

  • the first sorted field is first field in the index. (condition 1)
  • the last field in the index before the first sorted field is an equality match in the query. (condition 2)
=> query must be satistfy or(condition 1,condition 2) or and (condition 1, condition2) to take advantage of Index?
Example: Give the following index
{ a: 1, b: 1, c: 1, d: 1 }
and which query search and sort use index to improve performance? and why?

db.collection.find().sort( { a:1 } )
db.collection.find().sort( { a:1, b:1 } )

db.collection.find( { a:4 } ).sort( { a:1, b:1 } )
db.collection.find( { b:5 } ).sort( { a:1, b:1 } )

db.collection.find( { a:{ $gt:4 } } ).sort( { a:1, b:1 } )

db.collection.find( { a:5 } ).sort( { a:1, b:1 } )
db.collection.find( { a:5 } ).sort( { b:1, c:1 } )

db.collection.find( { a:5, c:4, b:3 } ).sort( { d:1 } )

db.collection.find( { a:5, b:3, d:{ $gt:4 } } ).sort( { c:1 } )
db.collection.find( { a:5, b:3, c:{ $lt:2 }, d:{ $gt:4 } } ).sort( { c:1 } )
 
db.collection.find().sort( { b:1 } )
db.collection.find( { b:5 } ).sort( { b:1 } )
db.collection.find( { b:{ $gt:5 } } ).sort( { a:1, b:1 } )

Thanks so much!!
Phuc,
Cheers...
 

Gianfranco

unread,
Sep 17, 2012, 7:27:17 AM9/17/12
to mongod...@googlegroups.com
This queries are the only ones that don't use that index are:

db.collection.find().sort( { b:1 } )
db.collection.find( { b:5 } ).sort( { b:1 } )

This is because keys must be compared in the order in which they appear.

A simple way to see if a query uses the index is to append ".explain()" at the end, for example:

db.collection.find().sort( { a:1 } ).explain()

If the the cursor used is BasicCursor, then the index is not being used, if it does the BtreeCursor and the name of the cursor will appear.

And if you want to see the indexes on that collection. You can run:

db.collection.getIndexes()

Reply all
Reply to author
Forward
0 new messages