1

I'm facing an issue while getting data from a mongoDB but this does not happen every time (which is difficult to track). Here is the situation :

I'm trying to get random data from a mongo collection by doing this :

var database = MongoClientWrapper.GetDb();
var coll = database.GetCollection<CollectionName>("CollectionName");

var collCount = (int)coll.Count();
var rnd = Helper.Getrandom.Next(0, collCount);
var sgs = coll.FindOneAs<CollectionName>(Query<CollectionName>.EQ( s => s.Id, rnd));

if (sgs == null) return null;

return sgs;

This is in a function which is called in a loop, I have to get this info for something like 15-20 items. And it works most times but sometimes it returns the same record for the 15 elements of the loop (I don't believe in coincidences). Do you think something like : var sgs = new CollectionName(); at the begining of the function would make the difference ? Any other idea?

Thank you.

fionaredmond
  • 639
  • 7
  • 15
Gun
  • 501
  • 8
  • 27
  • Are you seeding your random number generator ? See http://stackoverflow.com/questions/1785744/how-do-i-seed-a-random-class-to-avoid-getting-duplicate-random-values – Alex Dec 18 '15 at 10:29
  • No, i'm using new Random().Next() but whats the point of seeding Random() ? – Gun Dec 18 '15 at 10:43
  • 1
    Depending on your implementation your Random number helper can return the same value over and over again, see http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number – Alex Dec 18 '15 at 10:45
  • Great! I understand why it sometimes works! Thank you! – Gun Dec 18 '15 at 11:04

1 Answers1

1

You should initial your Random class with some Seed-Value, on which the number bases. I like the following one:

Random rnd = new Random(Guid.NewGuid().GetHashCode());

Hope this helps.

BendEg
  • 20,098
  • 17
  • 57
  • 131