Regular Expression + Options in MongoDB (C# Driver)

Viewed 1057

I'm working with the MongoDB driver for C # and I'm making queries to get from a collection a list of items that match a field.

I am using the BsonRegularExpression object with the following expression:

"/.*" + summonerName + "/"

This would be the equivalent of LIKE in Sql, but the problem comes when I want it to be case insensitive. To do so, many sites comment that it must be like this:

BsonRegularExpression expReg = new BsonRegularExpression("/.*" + summonerName + "/", "i");

When I put the options parameter like this: "i" after the expression, it just doesn't return anything.

I leave the entire code here:

public static List<Summoner> GetSummonerByName(String summonerName)
    {
        try
        {
            var database = dbClient.GetDatabase(databaseName);
            var collection = database.GetCollection<Summoner>(collectionSummoner);

            String nombreRegex = "";
            var nombreChar = summonerName.ToCharArray();
            foreach(Char caracter in nombreChar)
            {
                nombreRegex += "*";
                nombreRegex += caracter;
            }

            //var filter = Builders<Summoner>.Filter.Regex(u => u.name, new BsonRegularExpression("/.*C*o*r*b*a*n/"));
            BsonRegularExpression expReg = new BsonRegularExpression("/.*" + summonerName + "/");
            var filter = Builders<Summoner>.Filter.Regex(u => u.name, expReg);

            var resultado = collection.Find(filter).ToList();

            if(resultado.Count() == 0)
            {
                InsertSummoner(RiotApiConnectorService.GetSummonerByName(summonerName));
                GetSummonerByName(summonerName);
            }

            return resultado;
        }
        catch (Exception error)
        {
            return null;
        }
    }

Has anyone experience using regular expressions in the mongo driver in C #? Thanks in advance!

1 Answers

You should define it as

BsonRegularExpression expReg = new BsonRegularExpression(Regex.Escape(summonerName), "i")

The point here is that BsonRegularExpression regex definition should not include regex delimiters, / in your case. The regex instantiation is performed using the BsonRegularExpression class, and the regex delimiters are simply redundant, and are treated here as literal / in the pattern. There are no matches because your data have no slashes.

Next, you do not need .* here because regex searches for a match anywhere in the input text, it does not require a full string match (as is the case with LIKE operator).

Note Regex.Escape(summonerName) is used just in case there are special regex metacharacters in the summonerName, and if the method is not used, the search may fail.

Related