Ahmad H
Ahmad H

Reputation: 25

How to Handle Varying Parameter to Filter in MongoDB

In the product collection, I want to filter some of them based on the conditions.

Filter can have multiple fields that some of them could be empty.

For example, price range, type of product, color and etc.

Conditions will be received from clients in a Restful request.

What's the best practice to handle that?

Should I check the presence of each field and then add it to filters?

Upvotes: 1

Views: 543

Answers (1)

Kevin Smith
Kevin Smith

Reputation: 14456

I'd do the following, your API will have its own model that represents the query from the http request, this might look like the following

class Query
{
    public int? PriceLowerThan { get; set; }

    public int? PriceHigherThan { get; set; }

    public string? ProductType { get; set; }
}

Then you can map this into a bunch of filters by checking each property for if it's been set then building up a mongodb filter.

var query = new Query {PriceHigherThan = 10, ProductType = "Something"};

var filterDefinitionBuilder = Builders<Product>.Filter;
var filter = filterDefinitionBuilder.Empty;

if (query.PriceLowerThan.HasValue)
{
    filter = filter & filterDefinitionBuilder.Lt(x => x.Price, query.PriceLowerThan.Value);
}
if (query.PriceHigherThan.HasValue)
{
    filter = filter & filterDefinitionBuilder.Gt(x => x.Price, query.PriceHigherThan.Value);
}
if (query.ProductType != null)
{
    filter = filter & filterDefinitionBuilder.Eq(x => x.Type, query.ProductType);
}

// use filter
collection.FindAsync(filter);

class Product
{
    public int Price { get; set; }

    public string Type { get; set; }
}

Upvotes: 2

Related Questions