Search code examples
mongodbc#-4.0group-byfilteringmongodb-.net-driver

How to filter collection in Mongo C# driver?


I know Mongodb for Linq doesn't support group Operation!
So, I found group with Mongo C# driver as group by in LINQ.
I have read mongo-csharp-driver examples, but these are not group examples with filtering.
Please, tell me, thanks.

This is my code.

var Table = DatabaseLinq.GetCollection<Model.Urls>(TableName).FindAll().AsQueryable();
var queryData = (from item in Table
        group item by item.Url)
        .OrderByDescending(p => p.Sum(x => x.ViewsCount))
        .Skip((PageIndex - 1) * PageSize)
        .Take(PageSize);

This is my group by, but how can I add filter here?


Solution

  • You can add filter by using Find() instead of .FindAll() method, like this:

    var Table = DatabaseLinq.GetCollection<Model.Urls>(TableName)
      .Find(Query<Model.Urls>.EQ(x => x.Url, "Ken")).AsQueryable();
    var queryData = (from item in Table
            group item by item.Url)
            .OrderByDescending(p => p.Sum(x => x.ViewsCount))
            .Skip((PageIndex - 1) * PageSize)
            .Take(PageSize);