0

Using Linq in C#, one can write code such as:

public static class MyEntityExtensions {
    public static IQueryable<MyEntity> ByCodeSystem(IQueryable<MyEntity> items, int codeSystemId) {
        return items.Where(o => o.CodeSystemId == codeSystemId);
    }

    public static IQueryable<MyEntity> NotDeleted(IQueryable<MyEntity> items) {
        return items.Where(o => !o.Deleted);
    }
}

and then use it like this:

DbSet<MyEntity> allMyEntities = myDbContext.MyEntities;
var myFilteredEntities = allMyEntities
    .ByCodeSystem(42)
    .NotDeleted()
    .Select(e => new { Id = e.Id, Name: e.Name })
    .ToArray(); // Materialize only the filtered ones and project only the needed data

How can one do this when querying MongoDb and its native API? I know that a collection can be used exactly like this by using IMongoCollection.AsQueryable(), but certain mongo operators are more directly mapped by the native API (i.e.: Builders.Filter., Builders.Sort. ecc).

1 Answer 1

3

You can do the same with extension methods to extend the mongo filter builder, for your linq examples we could have:

public static class MyModelFilterDefinitionBuilderExtentions
{
    public static FilterDefinition<MyModel> IsNotDeleted(this FilterDefinitionBuilder<MyModel> filter)
    {
        return filter.Eq(x => x.Deleted, false);
    }

    public static FilterDefinition<MyModel> ByCodeSystem(this FilterDefinitionBuilder<MyModel> filter, int codeSystemId)
    {
        return filter.Eq(x => x.CodeSystemId, codeSystemId);
    }
}

We could then apply it using

mongoCollection.Find(Builders<MyModel>.Filter.IsNotDeleted());

Or apply multiple

var filter = Builders<MyModel>.Filter.IsNotDeleted() & Builders<MyModel>.Filter.ByCodeSystem(10);
mongoCollection.Find(filter);
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for answer. I would like to add there are Builders<MyModel>.Filter.And and Builders<MyModel>.Filter.Or for cascading filters using driver.
seems the only way for now. Until a less verbose one comes up, I'll accept the answer. Btw didn't know that bitwise operators were overloaded for chaining filters in boolean expressions... nice touch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.