Conditional Query based on Variable value in MongoDB

Viewed 350

I am building a list view page with multiple filters using .net core as backend and mongodb as database. I want to filter data based on some condition such that if the variable is passed as blank, it should retrieve all data, otherwise only the matching data.

In mssql this can be achieved easily by

where (@SymbolCode = '' or SymbolCode = @SymbolCode)

What is the option in mongodb filter

var filter = new BsonDocument
{   
    {
        "symbolCode", SymbolCodeSearchString // If string SymbolCodeSearchString is blank, it should retrieve all data else the search data
    }
};
            

Sample Data

{
    "_id": {
        "$oid": "60ed91bc65675f966c0eec46"
    },
    "symbolCode": "F",
    "timestamp": {
        "$date": "2021-07-13T13:14:35.909Z"
    }
}
2 Answers

you should check symboleCode before query on mongodb first check if symbolCode is empty or "" define filter query as

var filter = new BsonDocument
{   
    
};

else if it was not empty

var filter = new BsonDocument
{   
    {
        "symbolCode", SymbolCodeSearchString // If string SymbolCodeSearchString is blank, it should retrieve all data else the search data
    }
};

I was able to figure out. Thanks to @Naimi and @Takis. Building a dynamic filter is the key. Posting here the answer so that it could help anyone

var filterQuery = new BsonDocument
{
   {
    "symbolCode", new BsonDocument
     {
       { "$regex", SymbolCodeString},
       { "$options", "i"}
      }
    }
};

if (fromDate != "" && toDate != "")
{
  BsonElement dateFilter = new("timestamp", new BsonDocument
  {
     { "$gt", fromDate},
     { "$lt", toDate}
   });
   filterQuery.Add(dateFilter); 
}

By this way, i am able to add any number of filters dynamically

Related