0

I am trying to implement a (semi-) random result from MongoDB; I know, Q/A's a plenty, here on SO to. But... As I tried to query MongoDB, just for fun to see what I would get, $lte gives me some very strange results. Consider this dataset:

1. 0.011224885703995824
2. 0.01718393270857632
3. 0.03377954219467938
4. 0.09617210761643946
5. 0.10130057414062321
6. 0.13116577989421785
7. 0.25664394721388817
8. 0.27124307211488485
9. 0.3029055509250611
10. 0.31508319173008204
11. 0.3163822046481073
12. 0.34581731259822845
13. 0.5077376591507345
14. 0.5806738587561995
15. 0.5997774603310972
16. 0.6492975174915045
17. 0.710568506969139
18. 0.7257499841507524
19. 0.7275129975751042
20. 0.771076871547848

stored in a field called random, and filled with the rand-function. There is a index on this field, but with 20 records, I think that does not matter. But. If I query with: .findOne( {'random': { $lte : 0.59 }} ) I get the result: "random" : 0.34581731259822845 (number 12), while expecting number 14...? When I tried some more queries, the result is very strange. Sometimes it is what I expect, but most of the time it seems to... well, I don't know. I do not understand how the query above leads to the result it gives...

styvane
  • 59,869
  • 19
  • 150
  • 156
Paul Wiegers
  • 199
  • 1
  • 7
  • have you look [this](http://docs.mongodb.org/manual/reference/method/db.collection.findOne/) find one method returns the first document according to the natural order – Neo-coder May 28 '15 at 05:02
  • Sure, but it should return documents that statisfies the query. The returned result does not.. I feel. It's field "random" does _not_ meet the criteria? – Paul Wiegers May 28 '15 at 06:16
  • 0.34581731259822845 is less than 0.59 isn't it? Why wouldn't you expect this? – marijnz0r May 28 '15 at 07:54
  • Well, because I would expect 0.5806738587561995 to be first? (In this query.) Or does it take "the first record that comes to mind" that fullfils the query? Ie: would you need to first sort the table, and then pick a random one? – Paul Wiegers May 28 '15 at 10:35
  • Ah! I think I get it now - that is wat Yogesh meant: findOne takes the first document in the natural order that statisfies the criteria! Right. I did not get that. So that means that if the random number is high, it will often return the same number. So Yogeshes answer is correct - although he might have elaborated a bit :-) – Paul Wiegers May 28 '15 at 10:43

1 Answers1

0

Ah! I think I get it now - that is wat Yogesh meant: findOne takes the first document in the natural order that statisfies the criteria! Right. I did not get that. So that means that if the random number is high, it will often return the same number. So Yogeshes answer is correct - although he might have elaborated a bit :-)

Paul Wiegers
  • 199
  • 1
  • 7
  • just use `find({...}).limit(1).sort({'rand':1})`, but you won't get real statistically random values. – evilive Jun 02 '15 at 06:35