[DOCS-31] Document how to write performant queries Created: 15/Apr/10  Updated: 15/Aug/11  Resolved: 16/Apr/10

Status: Closed
Project: Documentation
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major - P3
Reporter: Karoly Negyesi Assignee: Unassigned
Resolution: Done Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Participants:
Days since reply: 13 years, 44 weeks, 5 days ago

 Description   

(Documentation written by Doug Green) Mongo uses btrees, and for the most part, indexes work the same in mongo as they do in mysql. For most examples below assume an index on a,b,c.

1. The sort column must be the last column used in the index.

  • good:
  • find(a=1).sort(a)
  • find(a=1).sort(b)
  • find(a=1,b=2).sort(c)
  • bad:
  • find(a=1).sort(c)
  • even though c is the last column in the index, a is that last column used, so you can only sort on a or b.
    1. The range query must also be the last column in an index, this is an axiom of 1 above.
  • good:
  • find(a=1,b>2)
  • find(a>1 and a<10)
  • find(a>1 and a<10).sort(a)
  • bad:
  • find(a>1, b=2)
    1. Only use a range query or sort on one column.
  • good:
  • find(a=1,b=2).sort(c)
  • find(a=1,b>2)
  • find(a=1,b>2 and b<4)
  • find(a=1,b>2).sort(b)
  • bad:
  • find(a>1,b>2)
  • find(a=1,b>2).sort(c)
    1. Conserve indexes by re-ordering columns used in straight = queries
  • If you have the following two queries, then you only need a single index, on a,b,d,c
  • find(a=1,b=1,d=1)
  • find(a=1,b=1,c=1,d=1)
  • When you need to sort this gets more difficult, and you might need two indexes
    1. Never use Mongo's $ne or $nin operator's
  • When excluding just a few documents, it's better to retrieve extra rows from Mongo and do the exclusion in php
    1. Never use Mongo's $exists operator
  • If you need to check for the existance of something, then you'll have to denormalize this value.

The doc is already in wiki notation so it must be easy to move.



 Comments   
Comment by Kyle Banker [ 16/Apr/10 ]

Added to the doc minus the final recommendation on $exists. If we can provide a clearer example, I think it'd be worth adding.

Comment by Marc Seeger [ 15/Apr/10 ]

If it doesn't exist and it is NOT a sparse index, it will be indexed as null.
So searching for non existant stuff can be done with a find for "null" on indexed fields

Generated at Thu Feb 08 07:37:47 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.