Home > Back-end >  C# MongoDB check if array contains strings case insensitive
C# MongoDB check if array contains strings case insensitive

Time:05-11

I'm new to MongoDB and I'm trying to check if an input array of strings has any values that matches with a nested array of strings on any document.

public IEnumerable<Cocktail> FindByIngredients(List<string> inputIngredients)
    {
        inputIngredients = inputIngredients.ConvertAll(ingredient => ingredient.ToLower());
        var filter = Builders<Cocktail>.Filter
            .AnyIn(x => x.IngredientList, inputIngredients);

        var cocktails = _collection.Find(filter).ToList();
       
        return cocktails;
    }

Currently, I got above, but it's not case insensitive, how would I go about making this case insensitive?

JSON document from collection

CodePudding user response:

You can specify the collation when executing the query and by that change the way that MongoDB handles strings. See this [link][1] for details.

For instance, if you want to use English-US as locale for querying, you can use the following code:

public IEnumerable<Cocktail> FindByIngredients(List<string> inputIngredients)
{
    inputIngredients = inputIngredients.ConvertAll(ingredient => ingredient.ToLower());
    var filter = Builders<Cocktail>.Filter
        .AnyIn(x => x.IngredientList, inputIngredients);

    var options = new FindOptions() 
    {
      Collation = new Collation("en_US")
    };
    var cocktails = _collection.Find(filter, options).ToList();
   
    return cocktails;
}

If you do not specify a collation, a simple binary comparison is used, hence the distinction between upper und lower case.

If you want to support the query with an index, keep in mind that the index must also use the same collation that is used when querying. [1]: https://www.mongodb.com/docs/manual/reference/collation/

  • Related