0

Alright, first of all, we have a bunch of questions on this already:

One Random Record via Skip
Random Set via Skip

(SO thinks the other two links are code, I have no idea why - click edit and see references if you are interested)

My problem with all of these is that, if I understand correctly, skip is still going through all the records it skips, so it's slow. Looks like a new random method was added to mongoDb that gets a single random item from whatever matches find(). Is there some way to use this to get a set of records? Example from link...

photos.find({"author":"johndoe"}).random()

I could be completely misunderstanding. If not, would love to know how to do it and how to do it in .NET driver.

Edit: It seems like "Sample()" was added for C# Driver on Sep 18, 2015: https://github.com/mongodb/mongo-csharp-driver/commit/bd0383d66be2a76648968fbafaa36bf99c258b2d

public void Sample()
{
    var query = CreateQuery().Sample(100);

    Assert(query,
        2,
        "{ $sample: { size: 100 } }");
}

Doesn't work for me, but probably because I am running 2.0.

Community
  • 1
  • 1
VSO
  • 11,546
  • 25
  • 99
  • 187
  • 1
    `sample` was added in mongodb 3.2, and .net driver 2.2. – Alex Blex Feb 15 '16 at 22:45
  • 1
    All that really should matter is that your server is MongoDB 3.2. As long as it is then you can always just create the aggregation pipeline manually from BSON document contents ( since that it all that happens underneath anyway ). Whether there are "helper" methods in the driver or not are of little consequence. If your server is an earlier version, then it's back to [those earlier questions](http://stackoverflow.com/questions/2824157/random-record-from-mongodb) and answers for your solutions. – Blakes Seven Feb 16 '16 at 02:20

0 Answers0