Skip to content

Instantly share code, notes, and snippets.

@jeffdeville
Created September 10, 2010 21:46
Show Gist options
  • Save jeffdeville/574423 to your computer and use it in GitHub Desktop.
Save jeffdeville/574423 to your computer and use it in GitHub Desktop.
The index I've created
db.gift_ideas.ensureIndex({"sales_rank":1, "rated_by":1, "random":1});
The query, in it's fast form, but that does not return gift_ideas as ordered by the random field
db.gift_ideas.find({"sales_rank":{$lt:1200}, "rated_by":{$nin:["100001450582916"]}, "random":{$gt:0.6071995101094684}}).limit(40)
The query, in it's dog-slow form, where I enforce the sorting
db.gift_ideas.find({"sales_rank":{$lt:1200}, "rated_by":{$nin:["100001450582916"]}, "random":{$gt:0.6071995101094684}}).limit(40).sort({"random":1})
Field Info for gift_ideas:
sales_rank - Int
rated_by - Array
random - Float
-----------------------------
So suspecting that the problem is with sales_rank, I tried this instead:
db.gift_ideas.ensureIndex({"rated_by":1, "random":1});
Now when I run:
db.gift_ideas.find({"rated_by":{$nin:["100001450582916"]}, "random":{$gt:0.6071995101094684}}).limit(40)
It's fast as hell, but it isn't even using my index. As a result, still no sorting
The query, in it's dog-slow form, where I enforce the sorting
db.gift_ideas.find({"rated_by":{$nin:["100001450582916"]}, "random":{$gt:0.6071995101094684}}).limit(40).sort({"random":1})
Again, no index usage, just BasicCursor. So it's still too slow even when not doing that I need it to do.
-----------------------------
So I was able to force the use of the index, which accomplished what I wanted like so:
db.gift_ideas.find({"rated_by":{$nin:["100001450582916"]}, "random":{$gt:0.6071995101094684}})..hint({"rated_by":1,"random":1}).limit(40)
So the next plan I guess will be to just over-select, and then weed out the bad ideas, and just query iteratively until I have what I need.
I can do it in 2 shots, like this, and then do a simple select in memory from there.
db.gift_ideas.find({"rated_by":{$nin:["100001450582916"]}, "random":{$gt:0.6071995101094684}},{"sales_rank":1,"random":1}).limit(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment