12

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,

      }
   ]
}
HaBo
  • 13,999
  • 36
  • 114
  • 206

1 Answers1

2

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.

Taekahn
  • 1,592
  • 1
  • 13
  • 16
  • insensitive part is one and I also need to write query where text begins with, text ends with and text doesn't contain. I think I can only do such things with BsonRegularexpression? – HaBo Feb 20 '17 at 09:20
  • Sorry, i missed that as part of the question. The mongo driver will correctly handle a `String.StartsWith()` and `String.EndsWith()`, turning them into `/^` and `$/` respectively. it should also turn a unary not `!` into a mongo `$not: { }` – Taekahn Feb 20 '17 at 17:01
  • how about "does not contain" search? – HaBo Feb 22 '17 at 18:54