Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB random results in C# LINQ

Tags:

c#

linq

mongodb

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).

like image 299
PoeHaH Avatar asked Oct 07 '17 04:10

PoeHaH


2 Answers

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

like image 196
s7vr Avatar answered Sep 27 '22 21:09

s7vr


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.

like image 45
BOR4 Avatar answered Sep 27 '22 20:09

BOR4