Home > Back-end >  Dynamically Query a Mongo Collection in c#
Dynamically Query a Mongo Collection in c#

Time:11-24

I'm new to C# mongo,earlier worked on Node and Mongo. i have a collection called tasks.Below is a sample record.

{
    "_id" : ObjectId("6193bfba23855443a127466a"),
    "taskIdentifier" : LUUID("00000000-0000-0000-0000-000000000000"),
    "title" : "PR Liquidators",
    "company" : "iuytreugdfh",
    "purpose" : "test purpose",
    "column" : "Search",
    "assignTo" : "Shiva",
    "assignToId" : ObjectId("61933b47a79ac615648a7855"),
    "assignToImage" : null,
    "notes" : "ggh@William james ",
    "done" : 0,
    "taskID" : "00029",
    "status" : "Pending",
    "states" : [ 
        "Alabama - AL", 
        "Alaska - AK"
    ],
    "active" : true,
    "updatedAtUtc" : ISODate("2021-11-18T12:26:37.616Z"),
    "updatedBy" : ""
}

in my c# webapi Project i always get a array called filterCriteria from api request of below form:

filterCriteria=[
{key:"purpose",value:"test purpose",type:"eq"},
{key:"active",value:true,type:"eq"}
]

Now I want to query the mongo collection tasks using the given filterCriteria.

tried something using LINQ statements but no use --hardcoding works but dynamically not working. How can I achieve this???

CodePudding user response:

maybe you are looking for Builders:

public enum FilterType{
    eq=1,//equal
    gt=2//greater than
}
//************
var builder = Builders<FilterCritertiaModel>.Filter;
var query = builder.Empty;
foreach(var filterCriteriaItem in filterCriteria){
    switch (filterCriteriaItem.type) {
        case eq:
            query &= builder.Eq(filterCriteriaItem.Key, filterCriteriaItem.Value);
        case gt:
            query &=builder.Gt(filterCriteriaItem.Key, filterCriteriaItem.Value);
        //all cases....
}
  • Related