Gun
Gun

Reputation: 521

Getting random mongo DB record in C#

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.

Upvotes: 1

Views: 526

Answers (1)

BendEg
BendEg

Reputation: 21098

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.

Upvotes: 1

Related Questions