HaBo
HaBo

Reputation: 14317

Using MongoDB C# Driver write ElementMatch with Regex query

I need to construct the following query using MongoDB C# driver

db.Notes.find({ "Group._id" : 74, "CustomFields" : { "$elemMatch" : { "Value" : /batch/i } }, "IsDeleted" : false }).sort({ "CreatedDateTimeUtc" : -1 })

I used a query like this

builder.ElemMatch(x => x.CustomFields, x => x.Value.Contains(filterValue))

It generated mongo query as

db.Notes.find({ "Group._id" : 74, "CustomFields" : { "$elemMatch" : { "Value" : /batch/s } }, "IsDeleted" : false }).sort({ "CreatedDateTimeUtc" : -1 })

if you notice it is appending s at /batch/s instead of i /batch/i

How can I get this work? I need to do this for filters like

  1. contains, using .Contains()
  2. equals, thinking of using .Equals()
  3. doesn't contain, thinking of using !Field.contains(value)
  4. not equals to
  5. starts with
  6. ends with

Can I do something like this, so that I can apply all my regex patterns for all above filters.

builder.Regex(x => x.CustomFields[-1].Value, new BsonRegularExpression($"/{filterValue}/i"));

This converts the query to as below, but that doesn't get any results

db.Notes.find({ "Project._id" : 74, "CustomFields.$.Value" : /bat/i, "IsDeleted" : false }).sort({ "CreatedDateTimeUtc" : -1 })

FYI: builder is FilterDefinition<Note>

My sample Notes Collection is like this:

{  
   Name:"",
   Email:"",
   Tel:"",
   Date:02   /21/1945,
   CustomFields:[  
      {  
         Name:"",
         Value:"",
         IsSearchable:true,

      },
      {  
         Name:"",
         Value:"",
         IsSearchable:true,

      },
      {  
         Name:"",
         Value:"",
         IsSearchable:true,

      },
      {  
         Name:"",
         Value:"",
         IsSearchable:true,

      }
   ]
}

Upvotes: 12

Views: 2952

Answers (1)

Taekahn
Taekahn

Reputation: 1717

It sounds like all you're missing is the insensitive part. Have you tried this?

ToLower, ToLowerInvariant, ToUpper, ToUpperInvariant (string method) These methods are used to test whether a string field or property of the document matches a value in a case-insensitive manner.

According to the 1.1 documentation here, it says that will allow to perform a case insensitive regex match. The current documentation doesn't mention it, so just to be sure, i checked github and the code to create an insensitive match is still there.

Upvotes: 2

Related Questions