Search code examples
c#mongodbmongodb-querymongodb-.net-driver

Using $in clause for insensitive search in mongo db driver c#


I am wondering how to use the case insensitive for $in expressions.

According to the official MongoDB manual you can do this:

{ name: { $in: [ /^acme/i, /^ack/ ] } }

I tested out this on Compass and it's working fine, search is insensitive.

I need to this using the Mongo Driver in C#.

I am doing this:

  var array = new BsonArray(companyNames);

  var filter = new BsonDocument { { "Name", new BsonDocument { { "$in", new BsonArray(array) }} } };
  var result = _collection.Find(filter).ToList();

companyNames is a string[]

However this retrieves me only exact matches. It's kind of obvious because I am not including the "regex" expression. But I don't know how I am able to include the regex in a string.

The workaround is to create an $or expresion with regex for every company name.

Does anyone knows how to do this?

Thanks


Solution

  • With mongo-csharp-driver, you can utilise MongoDB.Bson.BsonRegularExpression. You can either perform:

    var arrayIn = new BsonArray().Add(
                          new BsonRegularExpression("^acme", "i")
                      ).Add(
                          new BsonRegularExpression("^ack"));
    var filter = new BsonDocument { { "name", new BsonDocument { { "$in", arrayIn }} } };
    var cursor = collection.Find(filter).ToList();
    

    Or alternatively, instead of string use Regex and RegexOptions:

    var arrayIn = new BsonArray().Add(
                          new BsonRegularExpression(
                              new Regex(
                                  "^acme", RegexOptions.IgnoreCase))
                      ).Add(new BsonRegularExpression(
                                  "^ack"));