I'm using MongoDB's linq driver to get my results from the database
mymongocollection.AsQueryable().Where(x => x.Type == 1);
Now I'd like to return 20 random records from the above. I've been searching but I can't find a proper way to do this with LINQ. I prefer not to do it in memory, but on the database. I found you can use MongoDB's $sample aggregation, but I don't know how to translate this into LINQ (if it's even possible).
I'm guessing you are using incorrect namespace like using System.Linq;, which provides access to IQueryable. 
You should instead use using MongoDB.Driver.Linq; which will give access to MongoQueryable implementation which has sample aggregation
You can try below aggregation in 2.4.0 driver version.
using MongoDB.Driver.Linq; 
collection.AsQueryable().Where(x => x.Type == 1).Sample(20); 
It outputs
{aggregate([{ "$match" : { "Type" : 1 } }, { "$sample" : { "size" : NumberLong(20) } }])}
Reference here
https://jira.mongodb.org/browse/CSHARP-1773
https://jira.mongodb.org/browse/CSHARP-1366
I went for full LINQ solution. Only problem is mongo didn't let me sort by non property so I had to call toList early to materialize query.
Selecting random results supported by this answer: Select N Random Records with Linq
var result = MongoCollection
            .AsQueryable()
            .Where(x => x.Type == 1)
            .ToList()
            .OrderBy(x => Guid.NewGuid())
            .Take(20)
            .ToList();
Hope it helps!
I think this will be executed in db (correct me if I am wrong):
var result = MongoCollection
            .AsQueryable()
            .Where(x => x.Type == 1)
            .AsEnumerable()
            .OrderByDescending(x => Guid.NewGuid())
            .Take(20)
            .ToList();
Just a little improvement but still executed in memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With