Building Mongo aggregation pipeline query with $regex search using C# Mongo driver

Viewed 247

I'm trying to build aggregate pipeline with value search according to the value with the C# mongo driver. The first stage would to filter where KeyA is "A" and then the second stage would be to do the search where I have a certain list of keys that I need to go over and compare their value with a regex, according to documentation the regex only checks strings and I need to check any type that the value can hold. I'm adding a model and code examples for what I have done so far but couldn't get to the expected end result, any help would be appriciated.

Model for example:

{ 
"_id" : ObjectId(), 
"KeyA" : "A", 
"KeyB" : NumberInt(5), 
"KeyNestedObj" : [
    {
        "KeyC" : "C"
    }, 
    {
        "KeyD" : "D"
    },
    {
        "KeyE" : NumberInt(5)
    }
 ]
}

Mongo shell query:

db.MongoTests.aggregate([{ "$match": { "KeyA": "A" }},
{ "$match": { "$or": [{ "KeyNestedObj": { "$elemMatch": { "KeyC": /^.*?Regex.*?$/ } } }, { "KeyNestedObj": { "$elemMatch": { "KeyE": /^.*?Regex.*?$/ }}}]}}])

C# query build:

var searchableFields = new List<SearchableField>
{
    new SearchableField{ Field = "KeyC" },
    new SearchableField{ Field = "KeyE" }
};

var searchableFieldsFilter = new List<FilterDefinition<Model>>();
var commonSearchBuilder = Builders<Model>.Filter;
var nestedObjSearchBuilder = Builders<KeyNestedObj>.Filter;

var searchValueRegex = new BsonRegularExpression($"^.*?{searchValue}.*?$");
foreach (var searchableField in searchableFields)
{
   var searchNestedField =
         commonSearchBuilder.ElemMatch(x => x.KeyNestedObj,
            nestedObjSearchBuilder.Regex(searchableField.Field, searchValueRegex));
   searchableFieldsFilter.Add(searchNestedField);
}

return Builders<ActivityDataModel>.Filter.And(searchableFieldsFilter);

Code aggregation query:

var renderedSearchQuery = searchStage.Render(mongoContext.Data.DocumentSerializer,
mongoContext.Data.Settings.SerializerRegistry);
var results= mongoContext.Data.Aggregate().Match(filterQuery).AppendStage<Model>(renderedSearchQuery).ToListAsync();
0 Answers
Related